Home > Software design >  NodeJS/MongoDB : Wanna condiotinally make a lookup only if a variable is true
NodeJS/MongoDB : Wanna condiotinally make a lookup only if a variable is true

Time:10-11

I want to check inside my lookup if surveyType field of my surveys document (foreign document) matches survey_type only if the survey_type query is provided.

export const fetchUserSurveys = (req: TypedRequestQuery<{survey_type:  string}, { id?: string }>, res: Response, next: NextFunction): void => {
  const {survey_type} = req.query
  User
    .aggregate([
      {$match: {_id: Types.ObjectId(req.params.id)}},
      {
        $lookup:
          {
            from: 'surveys',
            let: {survey_ids: '$respondedSurveys'},
            pipeline: [
              {
                $match: {
                  $expr: {
                    $and: [
                      {$in: [
                        '$_id',
                        '$$survey_ids',
                      ]},
                      {$eq: [
                        '$surveyType',
                        survey_type,
                      ]},
                    ],                  
                  },
                },
              },
            ],
            as: 'userSurveys',
          },
      },
      {$project: {_id: 0, userSurveys: 1}},
    ]).then(result => {
      result.length ? res.status(200).send({data: result}) : res.status(404)
    }) 
    .catch(err => {
      next(err)
      res.status(500).send()
    })
}

Only if the survey_type query is provided I want to make this check

{$eq: [
  '$surveyType',
   survey_type,
]}

Should I use a complete if clause here or is there a MongoDB idiomatic way of doing this?

CodePudding user response:

The better option is to do in nodejs side, and second, pass this condition outside $expr expression operator because we are checking value from an external variable.

{
    $match: {
        $expr: { $in: ['$_id', '$$survey_ids'] },
        ...(survey_type ? { surveyType: survey_type } : {})
    }
}
  • Related