I am working on a generic query method for an API (REST) using nodeJS, MongoDB and Express.
After the routes forward to my module the request, everything works as expected when performing literal queries. I am querying by example, but when I want to query with regular expressions or with 'like' in SQL terms, I am not being able to make it work.
The find method using express inside the module is this:
exports.findByQuery = function(req, res) {
collection.find( req.query).toArray(function(err, docs);
}
This works as expected, except that if I want to query for a field with a regular expression to find say all username that have T, I always get the .query JSON object as a string with "" like this :
{"username":"/T/"}
instead of :
{username:/T/}
The req.query is coming from a GET request.
If i replace the:
collection.find( req.query).toArray(function(err, docs);
with:
collection.find( {username:/T/} ).toArray(function(err, docs);
it works fine!..
I think I need to perform a sanitization or conversion method to req.query before performing the .find on it, but I can't find anything. Any clue or help would be greatly appreciated!
Thanks in advance for your help!
I found a solution.
I wasn't able to convert the objects directly to RegExp as explained in the comments below the quesiton. What I did is create a helper function to return a properly formatted regexp query for mongo, and then perform the .find into it.
So, the find will be:
exports.findByQuery = function(req, res) {
var query = req.query;
db.collection('users', function(err, collection) {
collection.find( parseRegExpProperties(query) ).toArray(function(err, docs) {
res.send(docs);
});
});
};
And here's the : parseRegExpProperties method. I don't know how safe is this, but it's at least a start for me :
function parseRegExpProperties(obj) {
var newObject = {};
for(var propName in obj) {
if(typeof(obj[propName]) != "undefined") {
newObject[propName] = {'$regex': obj[propName], '$options': "i"};
}
}
return newObject;
}
If someone has any comment's in regards to performance, or how safe is this, it would be very welcomed!