Mike Vayvala Mike Vayvala - 2 months ago 26
Javascript Question

Asynchronously loop through the mongoose collection with async.each

I am using

acync.series
on my node.js program. I am trying to asynchronously loop through the mongoose collection with
async.each
. Here is code so far:

var async = require('async');
var mongoose = require('mongoose');
var usersData;
async.series([
function(callback) {
mongoose.connect("mongodb://localhost/****");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error...'));
db.once('open', function callback() {
console.log('db opened!');
});
callback();
},
function(callback) {
users = mongoose.model('User', new mongoose.Schema({name: String,age: Number}));

users.find(function(err, userFound) {
if (err) {console.log(err);}
usersData = userFound;
});
callback();
},
function(callback) {
async.each(usersData, function(userData, callback) {
some code....
}, callback);
}
])


When I run it i get the following error from async:

if (!arr.length) {
^
TypeError: Cannot read property 'length' of undefined


What is the right way to asynchronously loop through the mongoose collection

Answer

I think in our case better use waterfall, like this

async.waterfall([
    function (callback) {
        mongoose.connect("mongodb://localhost/****");
        var db = mongoose.connection;

        db.on('error', console.error.bind(console, 'connection error...'));
        db.once('open', function () {
            callback(null);
        });
    },
    function(callback){
        var users = mongoose.model('User', new mongoose.Schema({
            name: String,
            age: Number
        }));

        users.find(function(err, userFound) {
            if (err) {
                return callback(err);
            }

            callback(null, userFound);
        });

    },
    function(usersData, callback){
        async.each(usersData, function(userData, callback) {

        }, callback);
    }
], function (err, result) {

});

There is good explanation about difference waterfall vs series

Comments