【问题标题】:mongodb nodejs lookup does not get data from the foreign tablemongodb nodejs查找没有从外部表中获取数据
【发布时间】:2021-02-13 08:41:32
【问题描述】:

我正在尝试在 mongodb 中执行查找以从两个表中获取数据。这是我到目前为止创建的内容:

  database.collection('surveys').aggregate([
             { $lookup:
                    {
                      from: 'questions',
                      localField: '_id',
                      foreignField: 'surveyId',
                      as: 'questions'
                    }
                  }
                 ]).toArray(function(err, res) {
                 if (err) throw err;
                 console.log(JSON.stringify(res));
               });

问题是我的调查表中的数据显示得很好,但我的问题表中的数据总是一个空数组,我不知道为什么。请在附件中找到我的数据库结构的两个屏幕截图。

【问题讨论】:

    标签: node.js mongodb lookup aggregation


    【解决方案1】:

    这很好用,所以您的问题可能是调查中的 _id 和问题上的surveyId 不匹配。提示:尝试使用像 Robo 3T 这样的 MongoDB 客户端来调试您的查询,而不是先在代码中进行。

    db.surveys.insert([
        { "_id" : "survey_1", "title" : "test" }
    ])
    
    db.questions.insert([
        { "_id" : "question_1", "isSeek" : true, "question" : "test", "surveyId" : "survey_1" }
    ])
    
    db.surveys.aggregate([
        { $lookup: { 
            from: 'questions', 
            localField:'_id', 
            foreignField:'surveyId', 
            as: 'questions'
        } }
    ])
    

    结果:

    {
        "_id" : "survey_1",
        "title" : "test",
        "questions" : [ 
            {
                "_id" : "question_1",
                "isSeek" : true,
                "question" : "test",
                "surveyId" : "survey_1"
            }
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 2019-01-16
      • 2020-06-21
      • 2013-01-15
      • 2015-04-11
      • 2016-02-27
      • 1970-01-01
      相关资源
      最近更新 更多