Mariano Coria Mariano Coria - 4 months ago 11
Javascript Question

How to wait for moongose to finish query?

router.post('/logout', function(req, res) {
if(req.body.newList){
var aux= JSON.parse(req.body.newList);
var aux1;
var i=0;
while(i<aux.length){
aux1=aux[i];
Task.findOne({username:aux1.username,text:aux1.text},function(err,res){
if(res){
i++;
}else{
task= new Task({username:aux1.username,text:aux1.text,state:aux1.state});
task.save(function(err){
i++;
});
}
});
}
}


Well, I have this so far. aux stores an array of json objects, they dont have an
_id
, so.. I need to iterate through them saving one by one when needed. Problem is (I figure) async, cause this code is saving in the data base only the last element of the array n times, being n the amount of diferent elements which should be saved**(see example). So, I think the async behavior of moongose querys is giving me the headache. Probably keeps iterating waiting for the result of the query, and then save with the last value of the array.

** for instance, if I have these values for save
[{username:'x',text:'a'},{username:'x',text:'aa'},{username:'x',text:'aaa'}]
..

It saves
[{username:'x',text:'aaa'},{username:'x',text:'aaa'},{username:'x',text:'aaa'}]


I tried using promises, but it didnĀ“t work.. Probably used them wrong

Answer

For such things I prefer using the caolan's async library. Simply do:

npm install async to add the module.

Then replace your code with:

router.post('/logout', function(req, res) {
    if (req.body.newList) {
        var aux = JSON.parse(req.body.newList);
        var async = require("async");
        async.each(aux, function(aux1, callback) {

            Task.findOne({
                username: aux1.username,
                text: aux1.text
            }, function(err, res) {
                if (res) {
                    callback();
                } else {
                    task = new Task({
                        username: aux1.username,
                        text: aux1.text,
                        state: aux1.state
                    });
                    task.save(function(err) {
                        callback();
                    });
                }
            });
        }, function(err) {
            // if any of the query processing produced an error, err would equal that error
            if (err) {
                // One of the iterations produced an error.
                // All processing will now stop.
                console.log('A query failed to process');
            } else {
                console.log('All queries have been processed successfully');
                //do other things here
            }
        });
    }
});