【发布时间】:2021-12-16 01:52:51
【问题描述】:
我有两个集合用户和帖子。我正在构建类似于 Facebook 的东西。如何为 cmets 设计架构,以便我可以为 cmets 提供 cmets(应该能够在任何深度回复评论)
【问题讨论】:
-
创建一个评论模型,引用回复评论作为数组,每条评论都应该插入到 cmets 集合中
标签: mongodb mongoose database-design
我有两个集合用户和帖子。我正在构建类似于 Facebook 的东西。如何为 cmets 设计架构,以便我可以为 cmets 提供 cmets(应该能够在任何深度回复评论)
【问题讨论】:
标签: mongodb mongoose database-design
在这里我有我的查询来查找每个用户/登录用户的评论 - 只需传入 ID:
db.comments.find({
"$or": [
{
"_uid": 1
}
]
})
我的数据是这样的:
db={
"comments": [
{
"_uid": 1,
"city": "New York",
"comments": "top comment"
},
{
"_uid": 2,
"city": "Seattle",
"comments": "middle earth is where the beasts love"
},
{
"_uid": 3,
"city": "Seattle",
"comments": "i love comment systems"
}
]
}
结果:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"_uid": 1,
"city": "New York",
"comments": "top comment"
}
]
如果我想查找所有 cmets:
db.comments.find({})
如果我想在每个 POST 中查找所有 cmets,那么可以稍微修改数据并将 POST URL 添加到对象:
db={
"comments": [
{
"_uid": 1,
"city": "New York",
"comments": "top comment",
"postUrl": "/posts/postID=12345"
},
{
"_uid": 1,
"city": "New York",
"comments": "top comment",
"postUrl": "/posts/postID=12345"
},....
]
}
现在我们可以从 POST '12345' 查询所有 cmets:
db.comments.find({
"postUrl": "/posts/postID=12345"
})
结果:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"_uid": 1,
"city": "New York",
"comments": "top comment",
"postUrl": "/posts/postID=12345"
},
{
"_id": ObjectId("5a934e000102030405000001"),
"_uid": 2,
"city": "Seattle",
"comments": "middle earth is where the beasts love",
"postUrl": "/posts/postID=12345"
}
]
【讨论】: