Skip to content

Instantly share code, notes, and snippets.

@gaarf
Created March 27, 2013 17:32
Show Gist options
  • Save gaarf/5256378 to your computer and use it in GitHub Desktop.
Save gaarf/5256378 to your computer and use it in GitHub Desktop.
Mongoose regexp not working?
I am using Mongo v2.0.2, and currently on Mongoose v3.6.0.
I have a collection called "Users". Each doc has a String field called "ua", which is NOT indexed - but I tried with an indexed field and the behaviour is the same.
I want to find all the docs that have a ua containing, say, "Safari". So I try to use RegExp queries.
-----
Directly in Mongo console, everything works fine:
db.users.find( { ua: { $regex: /safari/i } } )
db.users.find( { ua: /safari/i } )
(both return a set of documents)
-----
But when working through Mongoose, no such luck.
All the following queries return an empty set:
> User.find({ ua: /safari/i }).exec(console.log)
> User.find({ ua: { $regex: /safari/i } } ).exec(console.log)
> User.find().where('ua').regex(/safari/i).exec(console.log)
> User.find().where('ua').regex(new RegExp("safari", "i")).exec(console.log)
What does work is:
> User.find().where('ua').regex("Safari").exec(console.log)
> User.find({ ua: { $regex: "Safari" } } ).exec(console.log)
^ which is great, but I can't pass regexp options so I have to capitalize.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment