【问题标题】:How mongoose populate more than 2 level deep?猫鼬如何居住超过 2 层深度?
【发布时间】:2015-12-16 06:46:51
【问题描述】:

我将评论模型定义为:

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'}]
});

当我使用填充为:

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

我发现猫鼬只有一层深。那么我该怎么做才能让它填充一个以上的级别,因为级别可以是 2 或 3 或更多。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

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

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

    更新:

    看起来您的代码在不添加模型的情况下也能正常工作。所以问题应该出在其他地方,而不是在人口中。这就是你想要做的,对吧?

    【讨论】:

    • 您确定Comment.find({targetBlog: blog._id}) 从数据库返回Comment
    • 您确定添加model: 'Comment' 会帮助猫鼬填充不止一层吗?
    • 是的,我最近用过这个。
    猜你喜欢
    • 2016-12-27
    • 2015-02-18
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2021-07-18
    • 2015-02-09
    • 1970-01-01
    相关资源
    最近更新 更多