Home > Software design >  mongoose aggregate filter if param given
mongoose aggregate filter if param given

Time:10-21

I have an aggregation where the status and the id matches in the pipeline of a lookup. And in the collection there are some roles, which I get from request.query. If the role request is empty, I want to show every data. But if it isn't empty I want to show only the data where role is for example 'user'. The code which I have gives the result of that. But when the request.query is empty, it doesn't match and the result is empty.

How can I achieve that?

my current match stage

{
    $match: {
        $and: [
            {
              $expr: { $eq: ["$$id", "$_id"] },
            },
            { status: 1 },
        ],
        $or: [{ role: role }],
    },
},

CodePudding user response:

You can put JS condition, if role has value then return value otherwise empty object, and no need for $or operator,

{
    $match: {
        $and: [
            {
              $expr: { $eq: ["$$id", "$_id"] },
            },
            { status: 1 },
            role ? { role: role } : {}
        ]
    },
},
  • Related