简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM