为了账号安全,请及时绑定邮箱和手机立即绑定

使用猫鼬发表评论回复模式

使用猫鼬发表评论回复模式

慕容森 2022-12-22 14:30:39
我想不出一种方法来创建适当的模式来处理帖子、评论和回复。主要停留在我将如何处理对评论的回复上。基本上就像 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]})我制作的上述模式不处理对其他评论的回复。我还可以如何处理回复?
查看完整描述

1 回答

?
慕娘9325324

TA贡献1783条经验 获得超4个赞

如果您将评论 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并根据需要以图形方式显示它们。另一个可能的主要模式是,您不是从评论到帖子向上引用,而是从帖子到评论 [到评论等] 向下引用,这允许查找但不是那么简单的简单查询。


祝你好运!


查看完整回答
反对 回复 2022-12-22
  • 1 回答
  • 0 关注
  • 42 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信