【发布时间】:2016-02-08 22:14:55
【问题描述】:
我正在使用 mongodb 在 node.js 中编写一个 Web 应用程序。我有这段代码,但不幸的是它没有按顺序执行,我的意思是 for 循环的迭代速度比那些 db 函数的执行速度要快,这不会造成混乱。
hospitalsCollection.update({}, {$pull: {doctors: parseInt(id)}}, function(err, success) {
treatmentsCollection.update({}, {$pull: {doctors: parseInt(id)}}, function(err, success) {
hospitalsCollection.find({"_id": {$in: hospitalsIds}}).toArray(function(err, hospitalsList) {
for(i = 0; i < hospitalsList.length; i++) {
for(j = 0; j < hospitalsList[i].treatments.length; j++) {
var exists = false;
for(k = 0; k < hospitalsList[i].doctors.length; k++) {
doctorsCollection.find({"_id": parseInt(hospitalsList[i].doctors[k])}).toArray(function(err, doctorObj) {
for(l = 0 ; l < doctorObj.treatments.length; l++) {
if(doctorObj.treatments[l] == hospitalsList[i].treatments[j]) {
exists = true;
break;
}
}
});
if(exists)
break;
}
if(exists) {
break;
}
else {
hospitalsCollection.update({"_id": parseInt(hospitalsList[i]._id)}, {$pull: {treatments: parseInt(hospitalsList[i].treatments[j])}}, function(err, success) {
treatmentsCollection.update({"_id": parseInt(hospitalsList[i].teratments[j])}, {$pull: {hospitals: parseInt(hospitalsList[i]._id)}}, function(err, success) {
console.log(err);
});
});
}
}
}
for(i = 0; i < treatments.length; i++) {
doctorsCollection.aggregate([ {$project:{"treatments._id":1, "treatments.price":1}}, {$unwind:"$treatments"},{$match:{"treatments._id": parseInt(treatments[i])}}, {$sort:{"treatments.price":-1}}, {$limit:1} ], function(err, result) {
doctorsCollection.aggregate([ {$project:{"treatments._id":1, "treatments.price":1}}, {$unwind:"$treatments"},{$match:{"treatments._id": parseInt(treatments[i])}}, {$sort:{"treatments.price":1}}, {$limit:1} ], function(err, result2) {
var maxPrice = result[0].treatments.price;
var minPrice = result2[0].treatments.price;
treatmentsCollection.update({"_id": parseInt(treatments[i])}, {$set: {"maxPrice": parseInt(maxPrice)}}, function(err, success) {
treatmentsCollection.update({"_id": parseInt(treatments[i])}, {$set: {"minPrice": parseInt(minPrice)}}, function(err, success) {
console.log(err);
});
});
});
});
}
});
});
});
我真的不知道该如何处理。任何帮助将不胜感激。谢谢。
【问题讨论】:
标签: node.js loops for-loop asynchronous