跳到主要内容
CNode

请教mongoose查询中回调函数怎样能拿到查询参数的值?

社区
Jjohnsmith0602发布于 13 年前最后回复 13 年前
147150

我需要在一个for循环中进行数据库查询,如果没有匹配把对应的index存进一个数组。

for ( var index = 0; index < 100; index++) {
    mongooseModel.findOne({ id: index }, function (err, model) {
        if (!model) {
            array.push(index);
        }
    });
}

由于mongoose的回调函数是异步的,我这么写存的index值是有问题的。有什么办法能把查询参数传给回调函数呢?

查看回复

回复 (1)

B
blacktea#113 年前

试一下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就是你想要的
});

参与回复

登录后即可参与回复。登录