Model Methods: Find
Finding documents in the database collection in MerlinDB.
🪶 MerlinDB's find method is used to find
documents in a collection.The find, findOne, findMany methods are similar, the only thing that differentiates them is that the 'findOne' method allows you to find just one document in the database, the 'findMany' method allows multiple documents to be found, and 'find' allows both.
1 import MerlinDB, { Schema} from "@chrisaxxwell/merlin-db";2 //Or if you are using 'merlindb.max.js' just call 'new MerlinDB()'; 3 4 const merlin = new MerlinDB( ) ;5 merlin.connect( "USER-DATABASE") ; 6 7 const UserSchema = Schema( { 8 name: String , 9 age: Number 10 } ) ; 11 12 var userModel = merlin.model( "User", UserSchema) ;13 14 //userModel.find(<query(Object)>, <options>); 15 userModel.find( { age: 27 } ) .then( e => { 16 console.log( e) ; 17 //returns: 18 [ 19 { name: "Isabelle", age: 27 , id_: ...} , 20 { name: "Sam", age: 27 , id_: ...} , 21 { name: "Chris", age: 27 , id_: ...} , 22 //Other documents that act = 27 23 ]; 24 25 //If there is not even one occurrence, it returns: 26 [ ]; 27 } ) ;
The available options for the find methods are:
Decrypt (Object) (Learn more): Decrypts encrypted data.
- You insert a card number or any other data with the encrypt option into the collection;
- So you want to decrypt this card number.
Well, decryption happens as follows, you use the decrypt option, which has 3 properties:
secretKey {String} (Mandatory) - This is the secret key used in encryption, this key must be the same;
fields {Array} (Required) - It is an array with the fields you want to decrypt;
strength {String} - It is mandatory if used in encryption, see more in Schema Encrypt;
hash {String} - It is mandatory if used in encryption, see more in Schema Encrypt;
salt {Number} - It is mandatory if used in encryption, see more in Schema Encrypt;
iterations {Number} - It is mandatory if used in encryption, see more in Schema Encrypt;
All of the options above, if passed from encryption, must be used in decryption with the same values.
1 dataModel.find( 2 //query 3 { name: "Sam" } , 4 //options 5 { 6 decrypt: { 7 secretKey: <your-secret-key>, 8 fields: [ "cardNumber" ], 9 strength: "medium", 10 //... 11 } 12 } 13 ) .then( e => { 14 console.log( e) ; 15 //Decrypted date 16 } )
null (Number): If defined as -1 it guarantees that not one search is of type null.
1 dataModel.find( 2 //query 3 { name: { $ne: null } } , 4 //options 5 { 6 null: -1 7 } 8 ) .catch( e => { 9 console.log( e) ; 10 //'null' is not allowed! 11 } )
$ne (Object): You can allow the types that are accepted in when using Operador $ne, for example, suppose you want to allow only string type values and not allow number type values, define $ne: { string: *1 *[schema1], number: -1 }.
1 dataModel.find( 2 //query 3 { age: { $ne: 29 } } , 4 //options 5 { 6 $ne: { number: -1 } 7 } 8 ) .catch( e => { 9 console.log( e) ; 10 //Number is not a valid value 11 } )