mongodb - 在 MongoDB 中构建评论和喜欢/不喜欢系统的有效方法
问题描述
我正在创建一个目录网站,我希望允许用户能够喜欢/不喜欢条目并能够留下评论文本。我想知道为此创建数据库结构的最佳方法是什么。
在应用程序的单个条目页面上,我需要获取这些数据:
- 如果用户喜欢/不喜欢一个条目
- 喜欢和不喜欢的条目计数
- 参赛评论
所以你有什么建议?我应该如何将这三个模式连接在一起?
User {
...,
// do I need to referance anything?
}
Entry {
...,
// maybe I should reference Reviews here
}
Review {
...,
liked?: boolean,
review: string,
// Entry reference?
}
可能是更好的方法吗?请记住,我也需要计算喜欢和不喜欢的数量,这种情况经常发生。所以它需要非常有效。
解决方案
考虑您的数据结构非常重要,并且知道您将要实现哪些功能对您有很大帮助。有帮助的是将它分解成小块并尝试将它们组合在一起。
喜欢和不喜欢条目?2个简单的计数器!如果您想加载条目的所有评论,您需要知道哪些评论是关于该条目的,因此您需要参考。像这样拼凑起来会给你一个很好的干净的数据结构,你可以使用它。
下面我为您提供了数据结构的可能实现。
User {
...,
// For quick indexing(at the cost of storage space)
// you could keep a list of review references in user
reviews: string[]
// Array of objects that tracks whether a user has liked or disliked a certain entry
likes: [{entry: string, liked: boolean}]
}
Entry {
...,
// Reference to all the reviews
reviews: string[]
// Independent counter for likes and dislikes.
likes: int
dislikes: int
}
Review {
...,
// Reference to the user
userId: string
review: string,
}
推荐阅读
- php - 仅在使用本地资源时从 HTML 生成 PDF 需要很长时间
- azure - Azure ML 服务中的度量文档太大
- html - 如何将旁注与标记元素对齐在同一水平面上?
- html - Bootstrap 4 Carousel,背景为纯色,右侧为图像,左侧为文本
- excel - Calculate difference of two value with same ID
- php - Use define as you get function data return
- python - Flask SQLAlchemy - Default filter value if no results for provided filter
- cinema-4d - 在 Cinema 4D 中水平拉伸纹理
- microsoft-teams - Microsoft Teams:需要在自定义选项卡中为 Sharepoint 文档提供“在 Teams 中编辑”
- java - Quartz 作业正在运行 - 无法连接到 SFTP 服务器 - 连接重置