In Mongoose doc I didn't find an equivalent for $regex of MongoDb. Can you provide a simple Mongoose find()
with a regex expression?
Regular expression or Regex is a very important part of programming. It is usually used to find a pattern in a string.
To get all the values that contains part of a string using Mongoose find , we can use the $regex operator. Books. find({ "authors": { "$regex": "Alex", "$options": "i" } }, (err, docs) => {} );
The value of the $in operator is an array that contains few values. The document will be matched where the value of the breed field matches any one of the values inside the array.
Mongoose | findById() Function The findById() function is used to find a single document by its _id field. The _id field is cast based on the Schema before sending the command.
mongoose doc for find.
mongodb doc for regex.
var Person = mongoose.model('Person', yourSchema); // find each person with a name contains 'Ghost' Person.findOne({ "name" : { $regex: /Ghost/, $options: 'i' } }, function (err, person) { if (err) return handleError(err); console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation); });
Note the first argument we pass to mongoose.findOne function. "{ "name" : { $regex: /Ghost/, $options: 'i' } }". "name" is the field of the document you are searching. "Ghost" is the regular expression. "i" is for case insensitive match. Hope this will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With