mongodb からデータを取得する node.js および Express で実行されている Web サーバーがあります。mongodb ではコレクションが動的に作成され、新しく作成されたコレクションの名前は 1 つのメタデータ コレクション「プロジェクト」に格納されます。私の要件は、最初にメタデータ コレクションを反復してコレクション名を取得し、次に各コレクション内に入って、いくつかの条件に基づいて複数のクエリを実行することです。私のコレクション メタデータは動的であるため、 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
});
});
});
};