我在node.js程序中使用acync.series
。我试图用async.each
异步循环遍历mongoose集合。到目前为止,这是代码:
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集合的正确方法是什么
答案 0 :(得分:6)
因为async/await
将是ES7并且已经通过转换非常受欢迎,所以当谷歌搜索Mongoose和异步时,这是最好的结果。
虽然没有回答原来的问题,但我想我会留下这个以供将来参考。
使用本机Promise(注意所有用户并行处理):
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`
});
}
答案 1 :(得分:2)
我认为在我们的情况下更好地使用 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答案 2 :(得分:0)
另一种选择:
functionProcess = (callback) => {
userModel.find().cursor().eachAsync(user => {
return user.save().exec(); // Need promise
}).then(callback); //Final loop
}