[英]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: 如果Node JS中有新东西(我使用的是MongoDB,Express和Mongoose),那我很好,我有以下问题:
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. 有一个包含10个地址id的数组,我需要在做其他事情之前检查所有地址是否都在数据库中。 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:
我知道mongoose会进行异步查询,我尝试使用Bluebird( https://www.npmjs.com/package/bluebird )来做出承诺,但仍然没有运气:
Here are some atempts: 以下是一些尝试:
1st 1
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 第2
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. 即使数组只包含有效ID,第一次尝试的promise返回总是未定义 ,第二次尝试则是false 。
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
可能有一些方法可以宣传MongoDB,并使查询更容易,但你也可以创建一个promises数组并使用
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");
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.