我有從node.js異步查詢mongodb的問題。這裏是我的代碼在node.js和mongodb中處理異步數據庫查詢
var values = [];
var positives = new Array();
var negatives = new Array();
var server1 = new mongodb.Server('localhost',27017, {auto_reconnect: true});
var db1 = new mongodb.Db('clicker', server1);
db1.open(function(err, db) {
if(!err) {
db1.collection('feedback', function(err, collection) {
for (var i=0;i <5; i++) {
collection.find(
{value:1},
{created_on:
{
$gte:startTime + (i*60*1000 - 30*1000),
$lt: startTime + (i*60*1000 + 30*1000)
}
},
function(err_positive, result_positive) {
result_positive.count(function(err, count){
console.log("Total matches: " + count);
positives[i] = count;
});
}
);
collection.find(
{value:0},
{created_on:
{
$gte:startTime + (i*60*1000 - 30*1000),
$lt: startTime + (i*60*1000 + 30*1000)
}
},
function(err_negative, result_negative) {
result_negative.count(function(err, count){
console.log("Total matches: " + count);
negatives[i] = count;
});
}
);
}
});
} else {
console.log('Error connecting to the database');
}
});
其實,我試圖從數據庫中獲取一些值。然後我需要操縱這些值。這只是我需要從正計數中減去負計數,然後使用positivecount-negative計數初始化值數組。現在因爲結果是異步獲得的。我該如何操作這些值並將它們放入值數組中。
歡迎來到node.js簡單的控制流變得困難。 – usr