我在这里遇到挑战,我试图从同一个集合中的另一个子文档填充子文档。这可能吗?下面是我的示例模式
var chapter = new Schema({
title:String,
startPage:Number,
endPage:Number
});
var keyPoint = new Schema({
text:String,
mentionInChapter:[{
type: Schema.ObjectId,
ref: 'chapter'}]
});
var Book = new Schema({
title:String,
author:String,
chapters:[chapter],
keyPoints:[keypoint]
});
我在下面尝试过,它没有在keyPoints数组中填充chapterId。
Book.findById(ID).populate('章&#39)。EXEC(功能(ERR,DOC){ 如果(!ERR) 的console.log(DOC); });
有没有办法实现这一点,以便我检索的Book文档中填充了所有详细信息?
答案 0 :(得分:0)
您可以尝试使用Model.populate方法,如下所示:
var chapter = new Schema({
title:String,
startPage:Number,
endPage:Number
});
var keyPoint = new Schema({
text:String,
mentionInChapter:[{type: Schema.ObjectId, ref: 'chapter'}]
});
var Book = new Schema({
title:String,
author:String,
chapters:[chapter],
keyPoints:[keyPoint]
});
Book.findById(id)
.lean()
.populate('chapters keyPoints')
.exec(function (err, docs) {
if (err) throw err;
Book.populate(docs, {path: 'keyPoints.mentionInChapter'}, function (err, book) {
if (err) throw err;
console.log(book);
});
});
更新:版本2:
var chapter = new Schema({
title:String,
startPage:Number,
endPage:Number
});
var keyPoint = new Schema({
text:String,
mentionInChapter:[{type: Schema.ObjectId, ref: 'chapter'}]
});
var Book = new Schema({
title:String,
author:String,
chapters:[chapter],
keyPoints:[keyPoint]
});
Book.findById(id).exec(function (err, doc) {
if (err) throw err;
Book.populate(doc, {path: 'keyPoints.mentionInChapter'}, function (err, book) {
if (err) throw err;
console.log(book);
});
});