简体   繁体   中英

Node JS - Handling Multiple queries (promise, bluebird)

I'm kind if new in Node JS (I'm using MongoDB, Express and Mongoose) and I have the following problem:

There is an array with 10 address ids, and I need to check if All of the addresses are in the database before doing something else. I'm aware mongoose makes async queries, I've tried to use Bluebird ( https://www.npmjs.com/package/bluebird ) to make promises but still no luck:

Here are some atempts:

1st

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

2nd

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

Even if the array contains just valid ids the promise return is always undefined for the first attempt or false for the second.

Can anyone help me ?

There's probably ways to promisify MongoDB and make queries that makes this easier, but you could also just create an array of promises and use 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);
}

And then do

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

What you could try is something like this

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

You could even use "count" like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM