0

I have a variable in my Node function.

var storeId;

The value of storeId may or may not be undefined.

Now, if it is undefined, I do not want $match to filter out based on this parameter . If storeId has a value, $match should filter out based on storeId.

$match: {
       type: "abc",
      "_store._id":storeId?: //something like if else here 
    }

What should I add here ?

1
  • 1
    I'd just have if/else condition in my javascript to check if storeId is undefined, then I use the query without _store._id and if storeId has some value then use the query with _store._id Commented Jan 4, 2016 at 13:50

1 Answer 1

2

I would solve this by creating an empty object to match against and then populate it conditionally:

var match = {};
if (storeId != undefined) match.storeId = storeId;
if (type != undefined) match.type = type;
//...

and then use that object in the aggregation pipeline:

 { $match: match }
Sign up to request clarification or add additional context in comments.

Comments

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.