In Mongoose doc I didn't find an equivalent for $regex of MongoDb. Can you provide a simple Mongoose find()
with a regex expression?
1 Answer
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.
-
10Thanks - this was helpful - just one thing... if you have a variable seems that you don't need to include the '/'. just {$regex:myVar, $options:'I'}}. Adding the '/' either before the variable name or concatenating them did not work for me.– Farasi78Commented Mar 13, 2020 at 17:09
db.users.find({name: /peter/i});
?