javascript - 使用猫鼬发表评论回复架构
问题描述
我想不出一种方法来创建一个适当的模式来处理帖子、评论和回复。主要停留在我将如何处理对评论的回复。基本上就像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]
})
我制作的上述模式不处理对其他评论的响应。我该如何处理响应?
解决方案
如果您将评论 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
并根据需要以图形方式显示它们。如果不是从评论向上引用到帖子,而是从帖子引用到评论[到评论等],则可以使用另一种主要模式,这允许查找但不那么简单的查询。
祝你好运!
推荐阅读
- laravel - 将历史模式 Laravel 与 VueJS 一起使用时出错
- python - 附加到 Raw_input
- twilio - TWILIO_APP_TOKEN 与身份验证令牌相同吗?
- ssl - 为 gRPC 重新加载 Netty 服务器的 SSL 上下文
- scripting - 使用 SCR 脚本打开和关闭 AUTOCAD 文件
- node.js - 我们如何将参数传递给自定义 express-validator?
- android - 在 TextView 上设置文本时,在屏幕上显示文本需要很长时间
- python - 使用 Tkinter 的 Python 功能区应用程序
- mysql - 我对这个 SQL 项目非常迷茫。汉堡店的销售订单
- c# - 使用 LINQ 从列表中获取第一条记录