I'm trying to gather data from a MongoDB with Node JS to draw a graph later.
My goal is to collect all entries by hour of the day. In my collection there is a "created_at" field which stores a Date Object.
I'm trying to store the data in an array with 24 slots like this:
// padding the array for each hour of the day
var hours = new Array(23);
// defaulting the value for each hour to 0
for(var i=0; i<hours.length; i++){
hours[i] = 0;
}
db.collection.find({}, {"created_at": 1}, function(err, entry){
if (err){ doSomething(); }
else {
entry.forEach(function(item, index){
// get hour of the day from the Date object
h = item["created_at"].getHours();
h = parseInt(h);
// store hour of the day and count it up
hours[h]++;
console.log("#%s: %s", index, h);
});
}
});
console.log(hours);
Now when I log hours I get the array with the default values. ie [0, 0, 0, 0 ... 0]
I'm certain that the database has correct values as the console.log in the inner function gets correct data.