Asynchronously move the mongoose collection using async.each

I use acync.seriesnode.js. in my program. I am trying to asynchronously scroll through a collection of mongooses with async.each. Here is the code:

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 correct way to loop asynchronously in a mongoose collection

+4
source share
3 answers

I think in our case it’s better to use a 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 a good explanation about the difference between the waterfall and the series.

+2
source

async/await ES7 , , googling Mongoose async.

, , .

native Promises ( , ):

const User = mongoose.model('User', new mongoose.Schema({
  name: String,
  age:  Number
}));


function processUsers() {
  return mongoose.connect('mongodb://localhost')
    .then(function() {
      return User.find();
    })
    .then(function(users) {
      const promises = users.map(function(user) {
        return // ... some async code using `user`
      });

      return Promise.all(promises);
    });
});


processUsers()
  .then(function() {
    console.log('Finished');
  })
  .catch(function(error) {
    console.error(error.stack);
  });

Mongoose eachAsync :

function processUsers() {
  return mongoose.connect('mongodb://localhost')
    .then(function() {
      return User.find().cursor().eachAsync(function(user) {
        return // ... some async code using `user`
      });
    })
});

async/await:

async function processUsers() {
  await mongoose.connect('mongodb://localhost');

  await User.find().cursor().eachAsync(async function(user) {
    await // ... some async code using `user`
  });
}
+4

Another option:

functionProcess = (callback) => {

  userModel.find().cursor().eachAsync(user => {
    return user.save().exec();        // Need promise
  }).then(callback);     //Final loop

}
0
source

Source: https://habr.com/ru/post/1568333/


All Articles