0

I have the following Documents in my MongoDB- database. This Document represents folders in my UI. A subfolder references to the parent folder over superFolderId.

I will view this tree in my angularJS UI. My question now would be how to store this tree structure in a list in backend in order to kindly show this structure in AngularJS Frontend.

I would be glad of any hint in this direction.

{
"_id" : ObjectId("598c43aa76eba30a8ab373ac"),
"name" : "Folder1",
"created" : ISODate("2017-08-10T11:29:41Z"),
"projectId" : "598c425d76eba30a8ab373a6",
"superFolderId" : "",
}
{
"_id" : ObjectId("598c43b176eba30a8ab373ad"),
"name" : "Folder1_1",
"created" : ISODate("2017-08-10T11:29:49Z"),
"projectId" : "598c425d76eba30a8ab373a6",
"superFolderId" : "598c43aa76eba30a8ab373ac",
}
{
"_id" : ObjectId("598c43f676eba30a8ab373ae"),
"name" : "Folder1_1_1",
"created" : ISODate("2017-08-10T11:30:58Z"),
"projectId" : "598c425d76eba30a8ab373a6",
"superFolderId" : "598c43b176eba30a8ab373ad",
}
quma
  • 5,233
  • 26
  • 80
  • 146

1 Answers1

0

You don't need to store tree on server side. Enough (regards to your example) _id record is a superFolderId for other record.

Once you get list of records on client side, you can easily convert it to tree as:

function _makeTree(options) {
    var children, e, id, o, pid, path, path_obj, temp, _i, _len, _ref;
    id = options.id || "id";
    pid = options.parent_id || "parent_id";
    children = options.children || "children";
    path = "path";
    path_obj = "path_obj";

    temp = {};
    o = [];
    _ref = options.q;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        e = _ref[_i];
        e[children] = [];
        e[path_obj] = [];
        temp[e[id]] = e;

        if (temp[e[pid]] != null) {

            e[path] = temp[e[pid]].path + '/' + e.name; // generates read-only String path to node

            e[path_obj] = _.clone(temp[e[pid]].path_obj);

            e[path_obj].push({name: e.name, id: e.id, org_id: e.org_id});

            temp[e[pid]][children].push(e);
        } else {
            e[path] = e.name;
            e[path_obj].push({name: e.name, id: e.id, org_id: e.org_id});
            o.push(e);
        }
    }
    return o;
};

**I took it from my project so some redundant stuff you can remove

Demo in fiddle


After that you can render tree like I posted HERE or just google it:

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225