Search code examples
regexmongodbmongoose

How to find items using regex in Mongoose


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


Solution

  • 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.