假设我有以下架构:
const QuestionSchema = new mongoose.Schema({
number: String,
question: { type: String, required: true },
submitter: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});
const QuizSchema = new mongoose.Schema({
name: { type: String, required: true },
questions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Question' }]
});
对于一个特定的测验,我知道如果我想填写问题,包括他们的提交者,我会这样做:
quiz.populate({
path: 'questions',
model: mongoose.model('Question'),
options: {
sort: { number: 1 }
},
populate: {
path: 'questions.submitter',
model: mongoose.model('User')
}
}).exec(cb)
现在是否可以在不同方法中分隔populate
次调用?
例如,我想做类似
的事情QuizSchema.methods.withQuestions = function () {
return this.populate({
path: 'questions',
model: this.model('Question'),
options: {
sort: { number: 1 }
}
});
};
QuizSchema.methods.withSubmitter = function () {
return this.populate({
path: 'questions.submitter',
model: this.model('User')
});
};
为了做到
quiz.withQuestions().withSubmitter().execPopulate().then(cb)
不幸的是,当我尝试这样做时,submitter
不会被填充。