我在从 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');
}
});
实际上,我正在尝试从数据库中获取一些值。然后我需要操纵这些值。只是我需要从正数中减去负数,然后用正数-负数初始化值数组。现在因为结果是异步获得的。我应该如何操作这些值并将它们放入 values 数组中。