MongoDB match if input exists (aggregation)

Viewed 87
$match: {
  date: { $gte: fromDate, $lte: toDate },
  if (userId) { 
    user: userId 
  }
},

I am trying to match a user only if there is a userId submitted. What is the best way to do this.

1 Answers

You can use mongoose query builder, to manage aggregations stages as per your conditions,

// INITIALIZE
let p = YourSchemaModel.aggregate();
// DATE FILTER
p.match({ date: { $gte: fromDate, $lte: toDate } });
// USER ID FILTER
if (userId) p.match({ user: userId });
// RESULT
let result = await p.exec();

Aggregation will auto merge $match stages if both are together!


Second option:

let result = await YourSchemaModel.aggregate().match(
  Object.assign(
    { date: { $gte: fromDate, $lte: toDate } }, 
    userId ? { user: userId } : {}
  )
).exec();
Related