我正在尝试对 mongo 数据库执行批处理操作。这个想法是遍历每个用户,然后找到正在学习同一类(class)或就读同一所大学的其他用户,并存储有关这些匹配项的信息。
一切都包含在这样的循环中:
User.find({}, function(err, doc){
doc.forEach(function(candidate){
//other find operations in here
...
}
}
其中“用户”是在网站上注册的用户的集合。我遇到的问题是 forEach 循环正在为每个用户分派(dispatch)所有回调,而我想等待 forEach 循环中的所有回调完成,然后再转到下一个文档。
我试过使用异步,但我似乎无法弄清楚这一点。
如何一次处理每个用户?
最佳答案
你可以为此使用async
,例如async.eachSeries
:
async.eachSeries(doc, function (candidate, cb) {
//other find operations in here
...
// and you call cb() once they're done (important!)
// or call cb('some error') if it failed
}, function (err) {
if (err) {
// this means that some cb() above was called with error
} else {
// here all candidates are processed successfully
}
});
关于node.js - NodeJS Batch Mongo 操作,等待回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42025562/