Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose complex queries with optional parameters?

I'm relatively new to Mongo & mongoose, and I've hit a problem.

I have a reasonably (for me anyway) complex query, that will allow the user to search for all entered terms.

so if the query is something like so:

var query = { '$and' : [
    { "foo1" : "bar1" },
    { '$and' : [ "foor2" : { $ne : null } }, { "foo2" : "bar2" } ] },
    { "foo3" : "bar3" }
]};

Doc.find(query);

but the user can enter any number of combinations for the parameters, i.e. I could search for all items that match foo1 & foo2, or just all items that match foo2, or just foo3, etc.

Is there a way to tell the query to only look for a parameter if it isn't empty, or is there a way to build searches like this programmatically? I have seen other options, for adding parameters like this, but they only seem to add in the standard

{ foo : 'bar' }

format, and for some reason they always seem to get added to query whether they meet the conditions of the if statement or not.

Thanks.

like image 692
user3075259 Avatar asked Jan 31 '26 15:01

user3075259


1 Answers

Firstly, you don't need $and operator for what you want. Comma separation is implicit and.

Your example query should simply be:

var query = {
    "foo1": "bar1",
    //"foo2": { $ne: null}, is unnecessary as "foo2" is being searched for "bar2" already, so it won't be null
    "foo2": "bar2",
    "foo3": "bar3"
};

To build this query dynamically, you can check the parameters (say req.body) one by one and add them to query object with 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, you can loop through the parameters and build the same query object if you are sure what they contain:

var query = {};

for(var key in req.body){ 
  query[key] = req.body[key];
}
like image 140
Talha Awan Avatar answered Feb 02 '26 07:02

Talha Awan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!