Search code examples
node.jsmongodbnode-async

How to properly get result array in async eachSeries for Node?


I'm trying to use async eachSeries in order to code what's the report count for every category. Categories and Reports and stored in separate collections, then I first get available categories and perform a count search on them.

This is my code:

    Category.find({},{_id:0, name: 1}, function (err, foundCategories) {
        async.eachSeries(foundCategories,
            function (item,callback) {
                Report.count({category: item.name}, function (err,count) {
                    var name = item.name;
                    console.log(count);
                   return callback(null,{name: count});
                });
            }
        ,function (err, results) {

            if (err)
                response.send(err);
            response.send(JSON.stringify(results));
        });
    });

The problem is that I'm receiving nothing, the console.log outputs actual numbers there, what am I doing wrong?


Solution

  • The API of eachSeries does not provide any results to the final callback - only an error in the failure case. In the success case, it's just a pure control flow "eachSeries is done" indicator, but does not provide a mechanism for passing values from the worker function. mapSeries does provide the functionality you need.