mongodb nodejs lookup does not get data from the foreign table

Viewed 187

i'm trying to perform a lookup in mongodb to get data from two tables. Here is what i have created so far:

  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));
               });

The problem is that the data from my survey table are shown well, but the data from my questions table are always an empty array and I don't know why. Please find attached two screenshots of my database structure.

question object

survey object

1 Answers

This works fine, so your problem is probably that the _id on survey and the surveyId on questions don't match. Hint: Try using a MongoDB client like Robo 3T to debug your queries instead doing it in code first.

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'
    } }
])

Result:

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