17

I have a following situation. I need to build a mongoose query, based on certain arguments if present.

I.e. if object like this is passed

{
    player: "nickname",
    action: "capture"
}

the following search is performed:

Entry.find({
    player: obj.player,
    action: obj.action
}).
    exec(function(err, res){
        console.log(res);
    });

If I need to exclude "action" from search if action is not in the object, what should I do? Using ternary operator like action: (obj.action) ? obj.action:null doesn't work, as would search entries in DB where action is null.

3 Answers 3

44

Build up your query object programmatically:

var query = {
    player: 'player'
};

if (obj.action) {
    query.action = obj.action;
}

Entry.find(query).exec(function(err, res){
    console.log(res);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Wow, didn't even think of that. Thanks a lot!
Does the order of fields in the query so created and the Entry model matter?
@JohnnyHK thanks.. and do you know if I want to search values greater than a particular range in this query-say there is a field called "budget" and we need to find all budgets greater than the given value?
10

With ES6, you can do this with a splat & ternary like this:

Entry.find({
  player: obj.player,
  ...obj.action ? { action: obj.action } : {}
})
.exec(function(err, res){
    console.log(res);
});

1 Comment

I favor this as it is a 1 liner
5

In case someone encounters same question, here's how I solved it:

var query = {
    player: 'player'
};

Entry.find({
    player: query.player,
    action: (query.action) ? query.action:/.*/
}).
    exec(function(err, res){
        console.log(res);
    });

2 Comments

A downside to this approach is that using the regex will hurt query performance. It's better to just omit the field from the query.
@JohnnyHK that's correct. 4 years on with ES6, you can avoid the regex with a splat & ternary

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.