如何在mongoose中填充多级数组

时间:2016-10-16 09:41:26

标签: mongodb mongoose mongoose-schema mongoose-populate

我有一个Quiz模型,其中包含Section数组,每个Sections都有一个对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}
});

和questionModel

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

    });

我已经按照正式的mongoose文档进行填充 http://mongoosejs.com/docs/populate.html#deep-populate

我的尝试

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

    });

  }

我得到的输出是问题ID列表而不是实际问题。

{
  "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"
          ]
        }
      ]
    }
  ]
}

我认为我在填充字段时遇到了问题,但不确定。

1 个答案:

答案 0 :(得分:0)

只需将您的查询更改为

即可
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id="iframe" src=""></iframe>