MongoDB:如何填充嵌入引用
MongoDB: How to populate an embedded reference
我不确定如何填充以下示例中 examBoard
集合中的 questions
字段(我故意使我的示例相当复杂,以便我可以正确理解它是如何有效)。
examBoard 架构:
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
});
});
我不确定如何填充以下示例中 examBoard
集合中的 questions
字段(我故意使我的示例相当复杂,以便我可以正确理解它是如何有效)。
examBoard 架构:
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
});
});