後でグラフを描画するために、Node JS を使用して MongoDB からデータを収集しようとしています。
私の目標は、1 日の時間ごとにすべてのエントリを収集することです。私のコレクションには、日付オブジェクトを格納する「created_at」フィールドがあります。
次のように、24 スロットの配列にデータを格納しようとしています。
// 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);
ログに記録hours
すると、デフォルト値の配列が取得されます。console.log
ie [0, 0, 0, 0 ... 0]内部関数が正しいデータを取得するため、データベースが正しい値を持っていることは確かです。