Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find items using regex in Mongoose [duplicate]

In Mongoose doc I didn't find an equivalent for $regex of MongoDb. Can you provide a simple Mongoose find() with a regex expression?

like image 939
Amio.io Avatar asked Jul 21 '16 07:07

Amio.io


People also ask

What is regex in mongoose?

Regular expression or Regex is a very important part of programming. It is usually used to find a pattern in a string.

How do you get all the values that contains part of a string using Mongoose find?

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) => {} );

What is $in in mongoose?

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.

What does find by id return mongoose?

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.


1 Answers

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.

like image 165
Shashith Darshana Avatar answered Sep 21 '22 18:09

Shashith Darshana