我讀到你可以製作Mongoose auto pouplate ObjectId字段。不過,我在構造查詢來填充子域中的字段時遇到了問題。如何使Mongoose的.populate()使用嵌入式模式/子文檔?
我的模型:
var QuestionSchema = new Schema({
question_text: String,
type: String,
comment_field: Boolean,
core_question: Boolean,
identifier: String
});
var SurveyQuestionSchema = new Schema({
question_number: Number,
question: {type: Schema.Types.ObjectId, ref: 'Question', required: true} //want this popuplated
});
var SurveySchema = new Schema({
start_date: Date,
end_date: Date,
title: String,
survey_questions: [SurveyQuestionSchema]
});
現在我這樣做達到的效果:
Survey.findById(req.params.id, function(err, data){
if(err || !data) { return handleError(err, res, data); }
var len = data.survey_questions.length;
var counter = 0;
var data = data.toJSON();
_.each(data.survey_questions, function(sq){
Question.findById(sq.question, function(err, q){
sq.question = q;
if(++counter == len) {
res.send(data);
}
});
});
});
這顯然是做的非常不容易出錯...
發現一個[錯誤線程(https://github.com/LearnBoost/mongoose/issues/601)和[路線圖](https://github.com/LearnBoost/mongoose/pull/1292)。目前都是。 – numbers1311407
Thanks @ numbers1311407!很高興知道。儘管如此,我開始認爲必須有一種方法可以重新組織我的模式,使其能夠與當前的實現一起工作。 –
也許一個愚蠢的問題(因爲我不知道超出這個應用程序的知識),但你真的需要'SurveyQuestion'? Mongoose數組的順序是有保證的,所以你不需要對它們進行排序。在不瞭解應用程序的情況下查看它,就會發現'Survey'可能只是嵌入'Question's。 – numbers1311407