I need some help regarding a JavaScript Callback problem.
I have a mongoldb-collection of samples in different levels. The structure looks like the following. I got documents in the form of:
{_id: "1", "parent": ""}, {_id: "2", "parent": "1"}, {_id: "3", "parent": "2"}
Now I want to query for all children of e.g. id="1" so that I get a JSON like this:
{_id: "1", "children": [{_id: "2", "parent": "1", "children": [{_id: "3", "parent": "2"}]}]}
I created a micro service and published the function with a API (see below).
And the loadChildren-function looks like:
loadChildren: function (id, cb) {
this.find({ parent: id }).exec(cb);
}
As can be seen, I'm trying to get multiple levels, but I'm stuck to make it recursive. What is the best way for this to get this to work. I also tried to use mongoose-tree and mongoose-path-tree but both do not work properly.
Thanks for all your help!!
What I have tried:
this.add('role:sample, cmd:children', function (msg, respond) {
Sample.loadChildren(msg.ID, function (err, samples) {
samples.forEach(function (children) {
children = children;
Sample.loadChildren(children._id, function (err, childchild) {
children.children = childchild;
childchild.forEach(function(children){
Sample.loadChildren(children._id, function(err, childX){
})
})
});
})
respond(null, { samples: samples });
});
});