猫鼬如何填充超过2级?

时间:2015-09-19 02:30:00

标签: node.js mongodb express mongoose

我将评论模型定义为:

CommentSchema = new mongoose.Schema ({
    name: String,
    email: String,
    website: String,
    content: String,
    createDate: Date,
    updateDate: Date,
    targetBlog: {type: mongoose.Schema.Types.ObjectId, ref: 'Blog'},
    childrenComment: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}]
});

当我使用populate as:

Comment.find({targetBlog: blog._id}).populate({path: 'childrenComment'}).exec(function(err, comments) {
    console.log(comments);
    res.render('blog', { blog: blog, comments: comments});
});

我发现mongoose只填充一层深度。那么我怎么能让它填充多个级别,因为级别可以是2或3或更多。

1 个答案:

答案 0 :(得分:0)

您可以在填充时手动指定模型。

Comment.find({targetBlog: blog._id})
    .populate({path: 'childrenComment', model: 'Comment'})
        .exec(function(err, comments) {
            console.log(comments);
            res.render('blog', { blog: blog, comments: comments});
});

<强>更新

看起来您的代码无需添加模型即可运行。所以问题应该在其他地方,而不是在填充。这就是你想要做的,对吧?

enter image description here