3

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.

1 Answer 1

3

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Cool thanks for that, I managed to figure out how to do it like this, but nice to know I came to the right solution. I think I'd made life a bit harder for myself by making a query that looked more complicated than it needed to be. Rookie mistake :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.