Node JS - 处理多个查询(promise,bluebird)

Node JS - Handling Multiple queries (promise, bluebird)

如果我是 Node JS 的新手(我正在使用 MongoDB、Express 和 Mongoose),我很友好,但我遇到以下问题:

有一个包含 10 个地址 ID 的数组,在执行其他操作之前,我需要检查 All 个地址是否在数据库中。我知道 mongoose 进行异步查询,我尝试使用 Bluebird (https://www.npmjs.com/package/bluebird) 来做出承诺,但仍然没有成功:

以下是一些尝试:

第一

var checkIds = function(idsArray){
    return new Promise(function(resolve, reject){
        var result = undefined;
        idsArray.forEach(function(id){
            Address.count({_id: id}, function(err, count){
                //count is 0 if id does not exist  
                if(err || !count){
                    reject(false);
                }
            });
        resolve(true); 
        });
    }
}

第二

var checkIds = function(idsArray){
    return new Promise(function(resolve, reject){
    var result = 0;
    for(var i = 0; i < idsArray.lenght; i++){
        Address.count({_id: idsArray[i]}, function(err, count){

            if(err || !count){
                reject(false);
            }else{
                result++;
            }

        });
    }
    resolve(result == 10 ? true : false);
    });
}

即使数组只包含有效的 ID,承诺 return 对于第一次尝试总是 undefinedfalse第二个

谁能帮帮我?

可能有一些方法可以承诺 MongoDB 并进行查询使这更容易,但您也可以只创建一个承诺数组并使用 Promise.all

var checkIds = function(idsArray){
    var promises = [];

    idsArray.forEach(function(id){
        var promise = new Promise(function(resolve, reject){

            Address.count({_id: id}, function(err, count){
                if(err or !count){
                    reject(false);
                } else {
                    resolve(true);
                }
            });
        }); 

        promises.push(promise);
    }
    return Promise.all(promises);
}

然后

checkIds(['id1', 'id2', 'id3']).then(function(values) {
    // success
}, function(reason) {
    // fail
})

你可以试试这个

model.find({ '_id': {$in: idsArray} }, function(err, docs) {
    if(docs.length == 10) {
        console.log("Your 10 docs with the 10 Ids are in your Database");
    }
})

你甚至可以像这样使用 "count"

model.count({ '_id': {$in: idsArray} }, function(err, count) {
    if(count == 10) {
        console.log("Your 10 docs with the 10 Ids are in your Database");
    }
})