I have a route in my API. When you apply to this router, the last 7 days are generated and on each day of the day the elements are extracted from the database. But apparently because of asynchrony, the sample does not work out as it should.
apiRoutes.get('/costs/chart', function (req, res) {
var currentDay = moment().format('L');
var currentWeekDays = [];
for (var i = 0; i < 7; i++) {
var day = {
date: (function () {
var date = moment().add(-[i], 'd');
return moment(date).format('L');
})(),
costs: []
};
Cost.find({formatDate: day.date}, function (err, costs) {
if (costs.length > 0) {
console.log(costs);
day['costs'] = costs;
}
});
currentWeekDays.push(day);
}
var result = {
content: {
currentDay: currentDay,
currentWeekDays: currentWeekDays
}
};
res.json(result);
});