Search code examples
javascriptnode.jsmongodbmongoosemongoose-populate

MongoDB: How to populate an embedded reference


I'm unsure of how would I populate the questions field in the examBoard collection in the following example (I have made my example reasonably complicated on purpose so I can properly understand how it works).

examBoard schema:

var topicSchema = new mongoose.Schema({
    name: String,
    questions:[
        {
            type:mongoose.Schema.Types.ObjectId,
            ref:"question"
        }
    ],
});

var moduleSchema = new mongoose.Schema({
    name: String,
    topics: [topicSchema]
});

var examBoardSchema = new mongoose.Schema({
    name: String,
    modules: [moduleSchema]
});

module.exports = mongoose.model("examBoard", examBoardSchema);

question schema:

var partSchema = new mongoose.Schema({
    mark: Number,
    content: String
});

var questionSchema = new mongoose.Schema({
    content: String,
    mark:Number,
    methods:[[partSchema]]
});

module.exports = mongoose.model("question", questionSchema);

How I thought I should do it:

examBoard.find()
    .populate
    ({
        path:"modules.topics.questions",
        model:"question"
    })
    .exec(function(err,exam)
    {
        if(err)
        {
            console.log("Failed to populate");
        }
        else
        {
            console.log("exam[0].modules[0].topcis[0].questions\n"+exam.modules[0].topcis[0].questions);
        }
    });

Solution

  • Try this:

    Exam
      .find()
      .exec()
      .then((exams) => {
        // Populate questions
        Exam
          .populate(exams, {
            path: 'modules.topics.questions',
            model: 'question'
          })
          .then((populatedExams) => {
            // Do something with populated exams
          });
      });