node.js - 更新嵌套树中的后代 mongoDB、node.js

标签 node.js mongodb tree

有没有办法通过 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:[]
                       }

                    ]

            },

            {
            },

            {
            },
        ]
     }
}

我使用The Node.JS MongoDB Driver

最佳答案

简而言之,没有真正好的方法来执行此类查询。有几个选项:

您可以使用长 $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/

相关文章:

javascript - 如何使用参数运行 npm {bin : script. js}

node.js - 推送到 Heroku 时出错 : Cannot find module 'node-linux-x64/package.json'

node.js - MongoDB 是否有使用类似 Mongoose 语法的(GUI)工具?

algorithm - 多次遍历树时,如何计算任意节点被访问的最大次数?

python - 从任意节点开始计算树中的内部(非叶)节点

node.js - nodejs脚本之间的socket.io通信

node.js - 在构建大型项目时如何在 polymer 中使用 --max-old-space-size 命令

python - Mongodb 与上一个条目的区别

mongodb - Mongoid 没有服务器可用匹配首选项

java - TreeSet 到 List 转换中的 Controller 排序