"$lookup with 'pipeline' may not specify 'localField' or 'foreignField'"

Viewed 9665

I'm new to mongoose & mongoDB, I have following query, which when run throws the follow error. It would be great if some can help me handle the issue and still get the same output

//interview.model.js => mongodb show name as interview
module.exports = mongoose.model('Interview', interviewSchema);
//candidate.model.js => mongodb show name as candidate
module.exports = mongoose.model('Candidate', candidateSchema);

const [result, err] = await of(Interview.aggregate([
         {
           $match: {
             ...filterQuery,
           }
         },
         {
           $lookup: {
             'from': 'candidates',
             'localField': 'candidateId',
             'foreignField': '_id',
             'as': 'candidateId',
             pipeline: [
               { $match: { 'candidateId.interviewCount': 0 }},
               { $project: { firstName:1, status:1, avatar:1 } }
             ]
           }
         },
       ]))
1 Answers

MongoDB 4.4 or below versions:

You can either use any one syntax of $lookup from 1) localField/ForeignField or 2) lookup with pipeline,

  • let to declare a variable candidateId you can use this id inside pipeline, that is called localField
  • pipeline push expression match using $expr and $eq because we are matching internal fields
  • $$ reference will allow to use variables in pipeline that is declared let
const [result, err] = await of(Interview.aggregate([
  { $match: { ...filterQuery } },
  { 
    $lookup: {
      'from': 'candidates',
      'as': 'candidateId',
      'let': { candidateId: "$candidateId" },
      'pipeline': [
        { 
          $match: { 
            $expr: { $eq: ["$$candidateId", "$_id"] },
            'candidateId.interviewCount': 0
          } 
        },
        { $project: { firstName:1, status:1, avatar:1 } }
      ]
    }
  }
]))

MongoDB 5.0 or above versions:

You query looks good as per latest version of mongodb, You can upgrade your mongodb version to mongodb latest version.

Related