MongoDB 中的嵌套注释

Ber*_*ant 5 comments nested mongodb

我对 MongoDB 很陌生,并试图用它构建一个嵌套的评论系统。在网上,您会找到各种文档结构来实现这一目标,但我正在寻找一些建议,使我能够轻松地通过评论执行以下操作

  • 将评论标记为垃圾邮件/已批准并通过此属性检索评论
  • 按用户检索评论
  • 检索对象/用户的评论计数

当然,除了像通常那样显示评论之外。如果您对如何使用 MongoDB 处理这些事情有任何建议 - 或者 - 告诉我寻找替代方案,我们将不胜感激!

And*_*ich 2

由于您需要按某些属性、用户等检索评论,因此您无法在用户可以评论的每个对象中嵌入评论(对于文档数据库来说,嵌入总是更快)。因此,您需要为评论创建单独的集合。我建议以下结构:

comment
{
  _id : ObjectId,
  status: int (spam =1, approved =2),
  userId: ObjectId,
  commentedObjectId: ObjectId,
  commentedObjectType: int(for example question =1, answer =2, user =3),
  commentText
}
Run Code Online (Sandbox Code Playgroud)

通过上述结构,您可以轻松完成您想要的事情:

//Mark comments as spam/approved and retrieve comments by this attributes
//mark specific comment as spam
db.comments.update( { _id: someCommentId }, { status: 1 }, true); 
db.comments.find({status : 1});// get all comments marked as spam

//Retrieve comments by user
db.comments.find({'_userId' : someUserId});

//Retrieve comment count for an object/user
db.comments.find({'commentedObjectId' : someId,'commentedObjectType' : 1 })
           .count();
Run Code Online (Sandbox Code Playgroud)

另外,我认为对于评论计数,最好在每个对象中创建额外的字段并将其包含在评论添加/删除中。