我需要在一个for循环中进行数据库查询,如果没有匹配把对应的index存进一个数组。
for ( var index = 0; index < 100; index++) {
mongooseModel.findOne({ id: index }, function (err, model) {
if (!model) {
array.push(index);
}
});
}
由于mongoose的回调函数是异步的,我这么写存的index值是有问题的。有什么办法能把查询参数传给回调函数呢?
1 回复
试一下async模块:https://github.com/caolan/async
var list = [0...100];
async.map(list, function (callback) {
mongooseModel.findOne({ id: index }, callback);
}, function (err, results) {
//results.filter(function (item) {return item;});//如果有需要过滤空值的话,当然也可以用async.filter
//results就是你想要的
});