Donnie Nguyen Donnie Nguyen - 4 months ago 23
Node.js Question

Mongoose - Multi-level navigation

i'm new to MongoDB & Mongoose

I have data like this:

{
"_id": "5787009e494495e56d327417",
"title": "Hahaha",
"parent": null,
"depth": 0
},
{
"_id": "5787009e494495e56d327416",
"title": "Hihihi",
"parent": null,
"depth": 0
},
{
"_id": "5787009e494495e56d327415",
"title": "Huhuhu",
"parent": "5787009e494495e56d327417",
"depth": 1
}


How can I convert the data into this:

{
"_id": "5787009e494495e56d327417",
"title": "Hahaha",
"children": [
"_id": "5787009e494495e56d327415",
"title": "Huhuhu",
"children": []
]
},
{
"_id": "5787009e494495e56d327416",
"title": "Hihihi",
"children": []
}


Please help me, and sorry for my bad english !

Answer

There is no other way you have to traverse the result and create new Data in memory.

//for each item in the result {
     if(item.parent !=null){
       insert_item_in_tree(item);   
     }
//}

then build a data structure function to insert the one item appropriately as per parent id.

Comments