网站评论系统

1,305 阅读1分钟

为自己博客网站设计一个评论系统

根据自己的设想,博客的评论系统应该是这样的:

  • 评论不作为一篇博客的一个子属性,作为一个单一实体使用一个外键id与一篇博客相连接
  • 评论会有一个parentId 作为检查是否是一个回复其他评论的评论, 如果没有parentId,那么这个评论就是直接回复这篇博客的评论
  • 评论内容
  • 评论者
  • 时间
  • ...待补充

博客数据库使用mongodb 已经有了一个初始化的评论collection, Schema 如下

// Comment Document Interface
export default interface IComment extends Document {
  commentedUser: string
  commentedUserId: string
  commentedDate: Date
  blogId: string
  content: string
}
// Comment Schema
const commentSchema: Schema = new Schema(
  {
    blogId: {
      type: String,
      required: true
    },
    parentId:{
        type:String,
        defualt:''
    },
    content: {
      type: String,
      required: true
      //   unique: true
    },
    commentedDate: {
      type: Date,
      default: Date.now
    },
    commentedUser: {
      type: String,
      required: true
    }
    conmentedUserId{
	type:String,
	required:true
    }
  },
  {
    //如果不想使用自定义用法直接可以写成 timestamps : true
    timestamps: { createdAt: 'commentedDate' }
  }
)

怎么样获取一篇博客的所有评论?

  • 有了上面的数据结构, 那么就可以使用blogId 获取一篇博客的所有评论.
  • 接下来获取到的所有评论直接最普通的json格式对象,评论的回复并不会更具parentId来做排序.
  • 需要在后台对数据进行处理, 将json对象转换成类似树形结构,
[
{id:"aaa",comment:'...',parentId:'' content:'',date:'',commentedBy:"",
comments:[{id:"bbb",comment:'...',parentId:'aaa' content:'',date:'',commentedBy:''}]}
]
  • 通过转换成这样的形式就可以对所有评论进行按照是否是博客的根回复进行归类

TODOs: 阅读一些评论系统数据结构设计 对自己评论系统进行一些优化