MongoDB模式:喜欢评论或帖子



我想在我的应用程序中设置一个"喜欢"系统。 用户应该能够喜欢帖子或评论(当然是帖子的评论(。我应该如何设计?

用户

const userSchema = new Schema({
id: { type: String, required: true },
username: { type: String, required: true },
password: { type: String, required: true },
});

职位

const postSchema = new Schema({
content: { type: String, required: true },
authorId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }
});

评论

const commentSchema = new Schema({
content: { type: String, required: true },
authorId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
postId: { type: mongoose.Schema.Types.ObjectId, ref: "Post", required: true },
});

喜欢

const likeSchema = new Schema({
content: { type: String, required: false },
authorId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
postId: { type: mongoose.Schema.Types.ObjectId, ref: "Post", required: function() { return this.commentId? false : true } },
commentId: { type: mongoose.Schema.Types.ObjectId, ref: "Comment", required: function() { return this.postId? false : true } }
});

我来自关系数据库,也许我的设计对于nosql来说是完全错误的。我的主要审问是关于喜欢的,我不知道如何接受帖子或评论上的喜欢。

我更喜欢一个单独的集合:

User:
id:  
...
Post:
id:
userId:
...
Comment:
id:
userId:
postId:
Like:
id:
userId:
postId:
commentId:

第二个存储数组将引导您在后端中的循环依赖项。特别是当你使用NodeJS和严格流动时。

MongoDB在存储文档方面非常强大。文档保存关系。 我会以访问数据的方式对其进行建模。我确实建议使用强大的聚合框架和数组运算符来体验这些可能性。我要探索的是以下内容

User:
id: 
name:
picture:
...
Posts:
id: 
authorid:
content:
total_views:
tags: array of String
likes: array of Likes {[
liked_by: user_id
],...}
comments: array of Comments {[
author_id: ...
comment: ...
reactions: array of Comments {[],...}
likes: array of Likes {[
liked_by: user_id
],...}
],...}

此模型会扩展吗?文档可以保存 16MB 的数据。16MB的文本格式是巨大的。

PS 请再次考虑在数据库中存储用户名/密码。这是另一个讨论。研究身份验证、授权、OAuth、哈希/加盐等主题。

post={
...keys,
likes:[likeSchema],
comments:[CommentSchema]
}

这是我更喜欢的,即使你想存储递归注释,也只需使用

commentschema={
id:unique commet id
text:...
user_id:who wrote this comment
parent_id: to which this comment belongs to!
depth: comment depth as your wish (mostly 2)
}

对于直接在帖子上发表的评论,家长 ID 将为空 家长 ID 将comment_id此评论所针对的评论。如果是递归注释。

希望你明白了。

因为,问题是关于像评论或帖子这样的架构。我会专注于喜欢。

构建这样的架构。在这里,targetId 将是postId 或 commentId

const likeSchema = new Schema({
content: { type: String, required: false },
authorId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
targetId: { type: mongoose.Schema.Types.ObjectId, ref: "Post", required: function() { return this.commentId? false : true } }
});

您需要考虑的几点:

  1. 在帖子集中存储帖子的赞
  2. 在评论集合中存储评论的赞
  3. 您需要构建一种机制来计算喜欢并存储在该集合中

最新更新