【问题标题】:"$lookup with 'pipeline' may not specify 'localField' or 'foreignField'""$lookup with 'pipeline' 可能没有指定 'localField' 或 'foreignField'"
【发布时间】:2021-06-19 06:07:39
【问题描述】:

我是 mongoose 和 mongoDB 的新手,我有以下查询,运行时会引发以下错误。如果有人可以帮助我处理问题并且仍然获得相同的输出,那就太好了

//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 } }
             ]
           }
         },
       ]))

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongodb-query


    【解决方案1】:

    MongoDB 4.4 or below versions:

    您可以使用$lookup 的任何一种语法,从 1) localField/ForeignField 或 2) 使用管道查找,

    • let声明一个变量candidateId你可以在pipeline里面使用这个id,也就是localField
    • pipeline 推送表达式匹配使用 $expr$eq,因为我们正在匹配内部字段
    • $$ 引用将允许在声明为 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:

    根据最新版本的 mongodb,您的查询看起来不错,您可以将您的 mongodb 版本升级到 mongodb 最新版本。

    【讨论】:

    • 看起来你可以同时使用MongoDB 5
    • @Kipr 它在 monngodb v5 中受支持,它是在一个月前推出的,这个答案是 6 个月以前的。将更新最新版本的答案。
    【解决方案2】:

    0

    使用 $lookup 中的管道,您不能使用 localField 或 foreignField。有关语法和示例,请参阅 MongoDB 文档here...

    【讨论】:

    • 是的,我查过了,但还是不明白如何处理我的问题
    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 2022-11-25
    • 2018-12-12
    • 2019-06-29
    • 2019-10-11
    • 2016-06-01
    • 2018-11-27
    • 1970-01-01
    相关资源
    最近更新 更多