mam*_*ood 1 javascript mongoose mongodb express
我想不出一种方法来创建一个合适的模式来处理帖子、评论和回复。主要停留在我将如何处理评论回复上。基本上就像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]
})
Run Code Online (Sandbox Code Playgroud)
我制作的上述架构不处理对其他评论的响应。我还可以如何处理回复?
如果您将评论 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,
},
})
Run Code Online (Sandbox Code Playgroud)
现在,当您加载帖子时,执行查询以获取所有评论并postId: post._id根据需要以图形方式显示它们。如果不是从评论向上引用到帖子,而是从帖子向下引用到评论[到评论等],则可能存在另一种主要模式,这允许查找,但不那么简单的简单查询。
祝你好运!
| 归档时间: |
|
| 查看次数: |
2008 次 |
| 最近记录: |