I'm new to nodejs and mongoose. I have a database dated from 2009 until now and would like to count number of data of each month, and return as json array. Slow async callback results all dates as Aug. 1, 2014
What is the proper way to implement this?
var dbURL = 'mongodb://localhost/database';
var db = require('mongoose').connect(dbURL);
var c_db = require('./models/models.js').c_db;
var start_date = new Date(2009,0,1);
end_date = new Date(2014,8,1),
next_date = new Date();
var test_json=[];
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
var next_date = start_date;
for(var i=0;i<total_months;i++){
var firstDay = new Date(next_date.getFullYear(), next_date.getMonth(), 1);
var lastDay = new Date(next_date.getFullYear(), next_date.getMonth() + 1, 0);
next_date.setDate(lastDay.getDate()+1);
c_db.count({'shipdate':{'$gte':new Date(firstDay),'$lte':new Date(lastDay)}},function(err,query){
var item = {
"Date": firstDay,
"Count": query
}
test_json.push(item);
});
}
setTimeout(function(){
console.log(test_json);
},5000);
c_db.count({'shipdate':{'$gte':new Date(firstDay),'$lte':new Date(lastDay)}},function(err,query){why are you doingnew Date(firstDay)? Are those not already date objects?whenFinished, that's called whentest_json.length === i - 1. Because of closures, if you put this aftertest_json.push(item), it'll call it, even if the for loop has finished looping. So something likeif (condition) whenFinished()on the line aftertest_json.pushshould work.