0

I'm facing this nested resource access to mongodb in Node.JS

I need to access to resources (let's call "resource_a") and their related sub-resources of the "resource_a" (let's call "resource_b"). I have a set of resource_b for each resource_a.

The code above is not working since it calls the callback on the first iteration. What is the best choice to get callback called as soon as all the resourceB calls are solved? Thanks, franco

function someFunction(err, callback){
    resourceA.find({}, function(err, resources_a){
        for(var resource in resources_a) {
            resourceB.find({"resourceA_Id":resources[resource]._id}, function(err, resources_b){
             // here some operation 
             callback(null, {"result":"..."}              
        }
    });
}

1 Answer 1

1

You need to wait until all the asynchronous subcalls are finished.

Usually this is done by using a call flow library (like https://github.com/caolan/async for instance).

you could lay out your own personal quick&dirty 'join' operation like so :

function someFunction(err, callback){
    resourceA.find({}, function(err, resources_a){
        var waiting = resources_a.length;
        for(var resource in resources_a) {
            resourceB.find({"resourceA_Id":resources[resource]._id}, function(err, resources_b){
             // here some operation 
             waiting--;
             if (waiting == 0) {
               callback(null, {"result":"..."}
             }              
        }
    });
}

(please note that this has not been tested, is not handling the case when resource_a is empty and is optimistic about the fact that all calls to resourceB will call their respective callbacks)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.