angular-ui-tree,从DATABASE中的数据填充树

时间:2016-08-25 23:34:21

标签: javascript angularjs arrays tree angular-ui-tree

我正在使用angular-ui-tree库来显示文件夹结构。

我将节点对象存储在MongoDB数据库中。

每个节点对象都是这样的

{
   "node_name" : "Folder 1",
   "node_path" : "AAABBB",
   "node_id" : 103,
   "node_parent_path" : "AAA",
   "node_parent_id" : 13,
   "template" : "Template 1"
}

Angular-UI-TREE以这种方式填充

data = [ {
           "node_name" : "Folder 1",
           "node_path" : "AAABBB",
           "node_id" : 103,
           "node_parent_path" : "AAA",
           "node_parent_id" : 13,
           "nodes" : [
                        {
                           "node_name" : "Folder 1-1",
                           "node_path" : "AAABBBAAA",
                           "node_id" : 10351,
                           "node_parent_path" : "AAABBB",
                           "node_parent_id" : 103,
                           "nodes" : [
                                        {
                                           "node_name" : "Folder 1-1-1",
                                           "node_path" : "AAABBBAAAAAA",
                                           "node_id" : 415,
                                           "node_parent_path" : "AAABBBAAA",
                                           "node_parent_id" : 10351,
                                           "nodes" : []      
                                         }
                                     ]
                         }, 
                         {
                           "node_name" : "Folder 1-2",
                           "node_path" : "AAABBBBBB",
                           "node_id" : 103531,
                           "node_parent_path" : "AAABBB",
                           "node_parent_id" : 103,
                           "nodes" : [

                                     ]
                         }, 
                     ]
         }, 
         {

           "node_name" : "Folder 2",
           "node_path" : "AAACCC",
           "node_id" : 104,
           "node_parent_path" : "AAA",
           "node_parent_id" : 13,
           "nodes" : []    
         }
]

使用此数据,树看起来像

Folder 1 
|
---> Folder 1-1
     |
     ---> Folder 1-1-1
|
---> Folder 1-2
Folder 2

使用上面显示的模式从mongoDB中存储的一堆节点中,我想填充DATA数组以便能够填充UI树..

最好的方法是什么?

或者有没有更好的方法将这些节点存储在数据库中,以便更容易检索该信息以填充树?

1 个答案:

答案 0 :(得分:1)

不确定您使用的是哪种服务器语言,因此我会将其保持一般化。
您有两个不同的选项,可以是递归查询,也可以从平面列表中构建嵌套列表。

1)递归查询: 编写一个函数来获取现有节点的所有子节点,获取根节点,并将结果作为子节点添加到现有节点,在返回的每个返回结果上运行递归查询函数。这将导致从根节点开始的适当结构。

2)关联数组: 从mongo获取所有节点,将它们放在由node_path键入的关联数组中。迭代此列表中的所有项目,添加到节点'使用parent_path作为关联数组的键的相应父级列表。然后从关联数组中通过路径获取根节点,并将其分配给数据'阵列。您也可以选择双重链接来强制执行父引用。

在答案1中,您可能需要“假”'根节点,如果根实际上是一个列表。在答案2中,您可能需要扫描关联数组中的所有项目以拉出没有parent_node的项目来创建基本根列表。随时可以通过更多信息询问后续信息

祝你好运!

相关问题