首页 > 解决方案 > 使用猫鼬发表评论回复架构

问题描述

我想不出一种方法来创建一个适当的模式来处理帖子、评论和回复。主要停留在我将如何处理对评论的回复。基本上就像reddit,他们发帖然后回复,你可以回复每个人的回复

视觉评论

在此处输入图像描述

(假设他们都在带有标题的帖子页面上回复)

const CommentSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
    },

    detail: {
        type: String,
        required: true,
    },


})


const PostSchema = new mongoose.Schema({
    author: {
        type: String,
        required: true,
    },
    title: {
        type: String,
        required: true
    },

    description: {
        type: String,
        required: true
    },
    comments: [CommentSchema]





})

我制作的上述模式不处理对其他评论的响应。我该如何处理响应?

标签: javascriptmongodbexpressmongoose

解决方案


如果您将评论 CommentSchema 硬合并到 Post Schema 中,您将始终受到硬编码的层数的限制。

相反,最好的做法是参考其他文档而不合并它们。例如(这只是众多方法中的一种):

comments: [CommentSchema]从 PostSchema 中删除。

const CommentSchema = new mongoose.Schema({

    // always require all comments to point to the top post, for easy query of all comments whether nested or not
    postId: {
        type: ObjectId,
        ref: 'posts',
        required: true,
    }

    parentCommentId: {
        type: ObjectId,
        ref: 'comments',
        required: false, // if not populated, then its a top level comment
    }
 
    username: {
        type: String,
        required: true,
    },

    detail: {
        type: String,
        required: true,
    },

})

现在,当您加载帖子时,请执行查询以获取所有评论postId: post._id并根据需要以图形方式显示它们。如果不是从评论向上引用到帖子,而是从帖子引用到评论[到评论等],则可以使用另一种主要模式,这允许查找但不那么简单的查询。

祝你好运!


推荐阅读