【问题标题】:Node JS - Handling Multiple queries (promise, bluebird)Node JS - 处理多个查询(promise,bluebird)
【发布时间】:2016-05-08 06:49:42
【问题描述】:

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

有一个包含 10 个地址 ID 的数组,在执行其他操作之前,我需要检查 所有 地址是否都在数据库中。我知道猫鼬会进行异步查询,我尝试使用 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,第一次尝试返回的 promise 总是 undefined 或第二次返回 false

谁能帮帮我?

【问题讨论】:

    标签: javascript node.js mongodb promise bluebird


    【解决方案1】:

    可能有一些方法可以对 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
    })
    

    【讨论】:

    • 谢谢 adaneo,我会试试的。
    • adaneo,效果很好,谢谢。然而,蒂埃里的回答是解决问题的好方法。
    【解决方案2】:

    你可以试试这样的

    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");
        }
    })
    

    你甚至可以像这样使用“计数”

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

    【讨论】:

      猜你喜欢
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 2014-09-28
      • 2021-08-12
      相关资源
      最近更新 更多