Using variables in a Regex MongoDB query in Node.js

A Blog Post by

I was busy writing a Node.js application with MongoDB integration when I came across this little problem with Regular expressions and MongoDB calls.
The following code will just return nothing:

var search = 'Joe';
db.users.find(name: /^search/);
db.users.find(name: {$regex: /^search/});
db.users.find(name: {$regex: "/^" + search + "/"});

The solution to this little problem is quite simple:

db.users.find(name: new RegExp(search));

I hate little issues like these.. so hope this helps someone else.

Created: Wed, 29/08/2012 - 18:19