I'm trying to calculate the amount of sign-ups of each day of the current month, and send that data to the Statistics page, where I display that data in a chart using Chart.js.
the data initialized well insides the query's scope, however I "lose" it outside of the scope.
EDIT - I extended my code so maybe there's some information relevant to my problem.
Here is my code:
async function getSignUps() {
const query = { createAt: { $gt: date.getFirstDateOfMonth(), $lt: new Date() } };
const projection = { createAt: 1, _id: 0 }; //can be added to find()
var signUps = new Array(date.getDaysInMonth()).fill(0); //create empty array of days in current month
Contractor_Users_Collection.find(query).project(projection).toArray(function (err, result) {
if (err) throw err;
// manipulte data to create array that the index indicates the day of month
// the value indicates the amount of signups per that day of the month
for (let i = 0, d = date.getFirstDateOfMonth(); i < result.length; i++, d.setDate(d.getDate() + 1)) {
nextDate = new Date(d.getDate() + 1);
if (d <= result[i]['createAt'] <= nextDate) {
day = result[i]['createAt'].getDate() - 1;
++signUps[day];
}
}
console.log('*****');
console.log('signUps inside find : ' + signUps);
console.log('*****');
})
console.log('*****');
console.log('signUps outside find : ' + signUps);
console.log('*****');
return signUps;
};
router.get("/statistics",async (req, res) => {
const signUps = await getSignUps();
console.log('*****');
console.log('signUps :' + signUps);
console.log('*****');
res.status(200).render("statistics", { signUps: signUps });
});
Here's the output :
*****
signUps outside find : 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
*****
*****
signUps :0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
*****
*****
signUps inside find : 1,3,3,5,4,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
*****