我有一个在 node.js 和 Express 中运行的网络服务器,它从 mongodb 检索数据。在 mongodb 中,集合是动态创建的,新创建的集合的名称将存储在一个元数据集合“项目”中。我的要求是首先迭代元数据集合以获取集合名称,然后进入每个集合内部根据某些条件进行多次查询。因为我的集合元数据是动态的,所以我尝试使用 for loop 来做。但它给出了错误的数据。它没有执行顺序。在完成循环执行之前,它返回值。如何仅使用节点核心模块在 node.js 中执行顺序执行(不是其他库,如 async ..);
exports.projectCount = function (req, res) {
var mongo = require("mongodb"),
Server = mongo.Server,
Db = mongo.Db;
var server = new Server("localhost", 27017, {
auto_reconnect: true
});
var db = new Db("test", server);
// global JSON object to store manipulated data
var projectDetail = {
projectCount: 0,
projectPercent: 0
};
var totalProject = 0;
db.open(function (err, collection) {
//metadata collection
collection = db.collection("project");
collection.find().toArray(function (err, result) {
// Length of metadata collection
projectDetail.projectCount = result.length;
var count = 0;
//iterate through each of the array which is the name of collection
result.forEach(function (item) {
//change collection object to new collection
collection = db.collection(item.keyParameter.wbsName);
// Perform first query based on some condition
collection.find({
$where: "this.status == 'Created'"
}).toArray(function (err, result) {
// based on result of query one increment the value of count
count += result.lenght;
// Perform second query based on some condition
collection.find({
$where: "this.status=='Completed'"
}).toArray(function (err, result) {
count += result.length;
});
});
});
// it is returning the value without finishing the above manipulation
// not waiting for above callback and value of count is coming zero .
res.render('index', {
projectDetail: projectDetail.projectCount,
count: count
});
});
});
};