In Mongoose doc I didn't find an equivalent for $regex of MongoDb. Can you provide a simple Mongoose find()
with a regex expression?
Asked
Active
Viewed 8.5k times
32

Amio.io
- 20,677
- 15
- 82
- 117
-
Maybe http://stackoverflow.com/questions/9824010/mongoose-js-find-user-by-username-like-value answers your question (quick Google search)? `db.users.find({name: /peter/i});`? – Wiktor Stribiżew Jul 21 '16 at 07:26
-
@WiktorStribiżew you are right. It helped. This one is good: http://stackoverflow.com/a/24791882/1075289 – Amio.io Jul 21 '16 at 07:45
1 Answers
77
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.

Shashith Darshana
- 2,715
- 1
- 25
- 27
-
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. – Farasi78 Mar 13 '20 at 17:09