Click here to Skip to main content
15,888,340 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:

JavaScript
{_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:

JavaScript
{_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:

JavaScript
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:

JavaScript
 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 });
    });
});
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900