有没有办法通过 id 或其他字段更新嵌套文档?
我使用“Full Tree in Single Document ”并且事先不知道嵌套可以有多深。需要更新,例如,用 {id:'104'} 回答。我可以通过“点表示法”来做到这一点,但由于我不知道嵌套的级别(深度),我无法预测我的 'comment.answers.answers....answers.'
可以去。
有没有办法直接查找并更新id:'104',或者我仍然需要传递某种深度标记?
{
title:'some title',
comment:
{
id:'101'
author:'Joe',
text:'some comment',
answers:
[
{
id:'102'
author:'Joe',
text:'first answer to comment',
answers:
[
{
id:'103'
author:'Done',
text:'first answer to first answer to comment',
answers:[]
},
{
id:'104'
author:'Bob',
text:'Second answer to first answer to comment',
answers:[]
}
]
},
{
},
{
},
]
}
}
最佳答案
简而言之,没有真正好的方法来执行此类查询。有几个选项:
您可以使用长 $or
语句创建查询,指定文档的每个可能的嵌套位置:
{ comment.id: 103, $or [
{ comment.answers.id: 103 },
{ comment.answers.answers.id: 103 },
{ comment.answers.answers.answers.id: 103 }
]
}
有关 $or operator see the docs 的更多信息.
事实上,更好、更可持续的解决方案是使用不同的模式,其中所有评论和答案都存储在一个平面数组中,然后将有关评论之间关系的信息存储在 comments.parent
字段。例如:
{ comment: [
{ id: 1 }
{ id: 2, parent: 1 }
] }
有关其他选项以及对评论层次结构建模的可能方法的更深入讨论,请查看 Storing Comments Use Case在 MongoDB 文档中。
Trees in MongoDB 中还有许多策略。您可能需要考虑。
关于node.js - 更新嵌套树中的后代 mongoDB、node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11271009/