Search code examples
mongodbmongoosemongoose-schemamongoose-populate

How to populate multilevel array in mongoose


I have a Quiz Model with array of Section and each Sections has array of reference to Question. I want to populate Quiz with question.

QuizModel

var quizSchema = new Schema({
    name: String,
    code: Number,
    creator: String,
    createdBy: { type: Schema.Types.ObjectId, ref: 'user' },
    section:[{
      title: String,
      questions: [{type: Schema.Types.ObjectId ,ref: 'question'}]
    }],
    createdOn: {type:Date, default:Date.now}
});

and questionModel

var questionSchema = new mongoose.Schema(
    {
      question: String,
      answer: [String],
      correct: Number,
      createdOn: {type:Date, default:Date.now}

    });

I have following the official mongoose documentation for populating http://mongoosejs.com/docs/populate.html#deep-populate

My attempt

  quizSchema.find({_id: quiz_id})
.populate({
  path: 'section' ,
  populate: {
    path: 'section.questions',
    model: 'questionSchema'
  }
})
.exec( function (err, result)  {

  if (err) return done(err,null);
  console.log("list of questions are" + result);
  return done(err, result);

    });

  }

The output I am getting is list of question's id not the actual question.

{
  "status": "success",
  "message": "Quiz data",
  "result": [
    {
      "_id": "57fd5912ec0ad6bc8b67d71c",
      "name": "My Quiz",
      "creator": "foo",
      "__v": 0,
      "code": 124,
      "createdOn": "2016-10-11T21:26:42.774Z",
      "section": [
        {
          "_id": "57fd7e82c20a2fe5da3ed569",
          "questions": [
            "57fd7f8560e98fe710878820",
            "57fd7f9d60e98fe710878821",
            "57fd81408b20dae9108d347c",
            "57fd81408b20dae9108d347d",
            "57fd826aea5159ea5ff2f1a9",
            "57fd82ab0dbc0feaa753e50c",
            "57fd82efd789afeb0353f036",
            "57fd84b0fef6a2ed21fad5ae",
            "57fd84cc5dab10ed471bcaf5",
            "57fd84cd5dab10ed471bcaf6"
          ]
        },
        {
          "title": "next section",
          "_id": "57fff1e0f1913138c27e50a0",
          "questions": [
            "57fff242f1913138c27e50a1"
          ]
        }
      ]
    }
  ]
}

I think I am doing something wrong with populate field, but not sure .


Solution

  • Just alter your query to

     quizSchema.find({_id: quiz_id})
    .populate({
      path: 'section.questions'
    })