Mongoose Schema从另一个集合填充数组字段

时间:2016-01-24 07:17:48

标签: node.js mongodb express mongoose

我有两个问题和答案,看起来像这样。

问题:

{ 
"_id" : ObjectId("56a450880c9a072eb092774f"), 
"text" : "Who are you?"
}

答案:

{ 
"_id" : ObjectId("56a452930c9a072eb092775f"), 
"text" : "I'm me!", 
"correct" : true, 
"question_id" : ObjectId("56a450880c9a072eb092774f")
}

然后我有两个模式:

AnswerSchema:

var answerSchema = new Schema({
answer: String,
correct: Boolean,
question_id : {type: db.Schema.Types.ObjectId, ref: 'Question'}
});

QuestionSchema

var  questionSchema = new Schema({
text: String,
answers : [answerSchema]
});

所以基本上,我想查询数据库以吐出像这样的答案填充的json:

{
_id: "56a451150c9a072eb0927751",
text: "Who are you?",
answers: [
  { "answer" : "I'm me!", "correct": true },
  { "answer" : "I'm you!", "correct": false },
  { "answer" : "You are you", "correct": false }
]}

我可以查询问题,但这样做不会填充答案:

    Question.find({})
    .populate("answers")
    .exec(function (err, questions) {
        //if(err) res.status(500).send(err);
        //else res.json(questions);
        res.json(questions);
});

我如何实现我想要做的事情。感谢。

1 个答案:

答案 0 :(得分:1)

由于answerSchemaQuestionSchema

的子文档
var questionSchema = new Schema({
   text: String,
   answers : [answerSchema]
});

为了满足您的要求,可以轻松完成

Question.find({})
    .exec(function (err, questions) {
        // all answers are in the every question as sub-document.
});

至于populate,何时需要

Question.find({})
  .populate("answers")
  .exec(function (err, questions) {
     //....
});

questionSchemaanswerSchema应为

var answerSchema = new Schema({
  answer: String,
  correct: Boolean
});
var Answer = mongoose.model("Answer", answerSchema);

var questionSchema = new Schema({
  text: String,
  answers : [{type: db.Schema.Types.ObjectId, ref: 'Answer'}]
});