【问题标题】:Asynchronously loop through the mongoose collection with async.each使用 async.each 异步循环遍历 mongoose 集合
【发布时间】:2015-02-18 11:48:36
【问题描述】:

我在我的 node.js 程序上使用acync.series。我正在尝试使用async.each 异步循环遍历猫鼬集合。这是到目前为止的代码:

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);
    }
])

当我运行它时,我从异步中收到以下错误:

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

异步循环遍历mongoose集合的正确方法是什么

【问题讨论】:

    标签: javascript node.js mongodb asynchronous mongoose


    【解决方案1】:

    另一种选择:

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

    【讨论】:

      【解决方案2】:

      因为async/await 将是 ES7 并且通过转译已经非常流行,所以这是在谷歌上搜索 Mongoose 和 async 时的最佳结果。

      虽然没有回答最初的问题,但我想我会把这个留作将来参考。

      使用原生 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`
        });
      }
      

      【讨论】:

      • 这是处理多个 mongoose 异步操作(使用 Promises)的最佳方式。
      【解决方案3】:

      我认为在我们的例子中最好使用 waterfall,像这样

      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) {
      
      });
      

      good explanation关于瀑布vs系列的区别

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-12
        • 2018-06-16
        • 2016-07-16
        • 2014-08-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多