gpt4 book ai didi

javascript - MongoDB:如何填充嵌入式引用

转载 作者:行者123 更新时间:2023-12-03 05:24:06 25 4
gpt4 key购买 nike

我不确定如何在以下示例中填充 examBoard 集合中的 questions 字段(我故意使示例变得相当复杂,以便我可以正确理解它是如何工作的)。

考试板架构:

var topicSchema = new mongoose.Schema({
name: String,
questions:[
{
type:mongoose.Schema.Types.ObjectId,
ref:"question"
}
],
});

var moduleSchema = new mongoose.Schema({
name: String,
topics: [topicSchema]
});

var examBoardSchema = new mongoose.Schema({
name: String,
modules: [moduleSchema]
});

module.exports = mongoose.model("examBoard", examBoardSchema);

问题架构:

var partSchema = new mongoose.Schema({
mark: Number,
content: String
});

var questionSchema = new mongoose.Schema({
content: String,
mark:Number,
methods:[[partSchema]]
});

module.exports = mongoose.model("question", questionSchema);

我认为我应该如何做:

examBoard.find()
.populate
({
path:"modules.topics.questions",
model:"question"
})
.exec(function(err,exam)
{
if(err)
{
console.log("Failed to populate");
}
else
{
console.log("exam[0].modules[0].topcis[0].questions\n"+exam.modules[0].topcis[0].questions);
}
});

最佳答案

试试这个:

Exam
.find()
.exec()
.then((exams) => {
// Populate questions
Exam
.populate(exams, {
path: 'modules.topics.questions',
model: 'question'
})
.then((populatedExams) => {
// Do something with populated exams
});
});

关于javascript - MongoDB:如何填充嵌入式引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41228540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com