首页 > 解决方案 > 在 MongoDB 中构建评论和喜欢/不喜欢系统的有效方法

问题描述

我正在创建一个目录网站,我希望允许用户能够喜欢/不喜欢条目并能够留下评论文本。我想知道为此创建数据库结构的最佳方法是什么。

在应用程序的单个条目页面上,我需要获取这些数据:

所以你有什么建议?我应该如何将这三个模式连接在一起?

User {
  ...,
  // do I need to referance anything?
}

Entry {
  ...,
  // maybe I should reference Reviews here
}

Review {
  ...,
  liked?: boolean,
  review: string,
  // Entry reference?
}

可能是更好的方法吗?请记住,我也需要计算喜欢和不喜欢的数量,这种情况经常发生。所以它需要非常有效。

标签: mongodbmongoose

解决方案


考虑您的数据结构非常重要,并且知道您将要实现哪些功能对您有很大帮助。有帮助的是将它分解成小块并尝试将它们组合在一起。

喜欢和不喜欢条目?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,
}

推荐阅读