是否可以用不同的方法分隔嵌套的填充调用?

时间:2017-07-08 17:45:27

标签: mongodb mongoose mongoose-populate

假设我有以下架构:

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不会被填充。

0 个答案:

没有答案