MongoDB模式:像评论或帖子

时间:2018-08-10 20:28:33

标签: mongodb mongoose

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

用户

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是完全错误的。我主要的询问是关于点赞,我不知道如何在“帖子”或“评论”上接受点赞。

3 个答案:

答案 0 :(得分:1)

我希望有一个单独的收藏夹:

User:
    id:  
    ...

Post:
    id:
    userId:
    ...

Comment:
    id:
    userId:
    postId:

Like:
    id:
    userId:
    postId:
    commentId:

第二个存储数组的对象将导致后端循环依赖。尤其是当您使用NodeJS并严格使用时。

答案 1 :(得分:0)

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,哈希/盐渍等主题。

答案 2 :(得分:0)

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。如果是递归注释。

希望你能得到它。