Wednesday, 4 October 2017

Handling asynchronous database queries in node.js and mongodb

I have this issue with querying mongodb asynchronously from node.js. Here is my code



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');
}

});


Actually, I am trying to get some values from the database. And then I need to manipulate these values. It's just that I need to subtract negative count from positive count and then initialize the value array with positivecount-negative count. Now since the results are obtained asynchronously. How am I supposed to manipulate those values and put them in the values array.

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...