strategesim strategesim - 3 months ago 15
Node.js Question

Nested asynchronous mongoDB calls in node js

I have quite a simple problem, but I can't find an elegant solution to fix this.
In the following code, I have two nested calls to a mongo DB. I use Monk to manage my calls.
The problem is : the for loop (1) loops before the nested insertion can happen. So the next find (2) instruction does not find the last inserted action.

The call order is 1-2-2-2-3-3-3 (for an actionList of size 3). So all my data is inserted.

My objective is to have the call order 1-2-3-2-3-2-3

Do you have any clue of how to manage such a problem, without making a big find on my database and manage my list server-side ? (Get all data, make myself the search, that is quite horrible to do, insert elements I want, then push it all to the db...)

for (var action of actionList)//(1)
{
collectionActions.find(//(2)
{eventid : action.eventid},
function(e,actionsFound)
{
if (actionsFound.length == 0)
{
collectionActions.insert(action, function(err, result)//(3)
{
console.log("insert action : " + action._id);
})
}
}
)
}

Answer

I finally got my solution, by using recursivity.

var currentIndex = 0;

var searchAndInsert = function(actionList)
{
    var action = actionList[currentIndex];
    if (typeof actionList[currentIndex] != "undefined")
    {
        collectionActions.find(
            {eventid : action.eventid}, 
            function(e,actions)
            {
                console.log("find ended")

                if (actions.length == 0)
                {
                    collectionActions.insert(action, function(err, result)
                    {
                        console.log("insert action : " + action.sourceName);
                        currentIndex++;
                        if (typeof actionList[currentIndex] != "undefined")
                            searchAndInsert(actionList);
                    })
                }
                else
                {
                    currentIndex++;
                    if (typeof actionList[currentIndex] != "undefined")
                        searchAndInsert(actionList);
                }
            }
        )
    }
};
Comments