Search code examples
node.jsmongodbmongoosemongoskin

Passing query conditions to db.collection.find in Node.js/Mongodb where the query string is generated


I am trying to build a NodeJS/mongodb application, where when I read a request which contains either (XYZ > 10) OR (XYZ < 15). I would like to generate a query string on the go. And then do a search in a certain Mongodb Collection. The following will work:

db.event.find( { 'data.XYZ': {'$lt':15} } ) // This works.

But I would like to do this:

var qstr1="{ \'data.XYZ\': {\'$lt\':15} // I would generate this possibly

db.event.find(qstr1)

When I try to pass the query condition as a string to db.collection.find() it returns me the entire collection.

I am using mongoskin for the application. This however does not work even via the Mongo Shell.

Is there a way to do this?


Solution

  • You're ultimately generating a query object, not a string, so build the query object up programmatically:

    var query = {};
    var field = 'data.XYZ';
    var operator = {};
    operator['$lt'] = 15;
    query[field] = operator;
    db.event.find(query);
    

    If you really want to keep things as a string, you can parse the string into a query object using JSON.parse:

    var qstr1="{ \"data.XYZ\": {\"$lt\":15} }";
    var query = JSON.parse(qstr1);
    

    Note that JSON.parse requires that keys are surrounded by double quotes (not single quotes) and isn't available in the shell.