0
var count = 0;
list.forEach(function(entry){
    var coll = db.collection(entry);
    coll.count(function(err,result){
       count = count + result;
    })
})

function(count){
//do something with count
}

I'm using the mongoDB native driver on node.js and the problem is that the function that is supposed to use count after it has done counted all the entries in each collection fires of to early, which is obvious as it asynch. I've searched after a solution for quite some time but haven't found anything yet.

  • 1
    I literally just did this at work. the mongo module is asynchronous, so the best method is to use a promise library (or native promises). I suggest bluebird or async – Sterling Archer Feb 18 '16 at 23:55

1 Answers1

1

You can use promises

Promise.all(
    list.map(function(entry){
        return new Promise(function(resolve, reject) {
            db.collection(entry).count(function(err, result){
                if (err) return reject(err);
                resolve(result);
            });
        });
    })
).then(count);

function count(result) {
    var sum = result.reduce(function(a,b) { return a + b });
}
adeneo
  • 312,895
  • 29
  • 395
  • 388