mongodb - Mongoose complex queries with optional parameters? -
i'm relatively new mongo & mongoose, , i've hit problem.
i have reasonably (for me anyway) complex query, allow user search entered terms.
so if query so:
var query = { '$and' : [ { "foo1" : "bar1" }, { '$and' : [ "foor2" : { $ne : null } }, { "foo2" : "bar2" } ] }, { "foo3" : "bar3" } ]}; doc.find(query);
but user can enter number of combinations parameters, i.e. search items match foo1 & foo2, or items match foo2, or foo3, etc.
is there way tell query parameter if isn't empty, or there way build searches programmatically? have seen other options, adding parameters this, seem add in standard
{ foo : 'bar' }
format, , reason seem added query whether meet conditions of if statement or not.
thanks.
firstly, don't need $and
operator want. comma separation implicit and
.
your example query should be:
var query = { "foo1": "bar1", //"foo2": { $ne: null}, unnecessary "foo2" being searched "bar2" already, won't null "foo2": "bar2", "foo3": "bar3" };
to build query dynamically, can check parameters (say req.body
) 1 one , add them query object bracket notation:
var query = {}; if (req.body.foo1) { query["foo1"] = req.body.foo1 } if (req.body.foo2) { query["foo2"] = req.body.foo2; } if (req.body.foo3) { query["foo3"] = req.body.foo3; }
or, can loop through parameters , build same query object if sure contain:
var query = {}; for(var key in req.body){ query[key] = req.body[key]; }
Comments
Post a Comment