First of all the function :
static async getInitRegistrationMetric(account) {
// we want only full day so we exclude current date
const exclude = DateTime.now()
.setZone('utc')
.startOf('day')
.toISODate();
// this count the number of client created by day.
const groupByDate = {
$group: {
_id: {
$dateToString: { format: '%Y-%m-%d', date: '$createdAt' },
},
count: { $sum: 1 },
},
};
// this is a way to rename (_id, count) to (date, value)
const renameData = {
$project: {
_id: 0,
date: '$_id',
value: '$count',
},
};
// this is done to filter data, I want to clean the null date and the today result
const excludeTodayAndNull = {
$match: {
$and: [
{
date: {
$ne: exclude,
},
},
{
date: {
$ne: null,
},
},
],
},
};
// account is the mongoose model.
return account.aggregate([groupByDate, renameData, excludeTodayAndNull]);
}
this code will produce data like this:
const data = [
{ date: '2000-10-01', value: 50 },
{ date: '2000-10-03', value: 12 },
{ date: '2000-10-07', value: 112 },
];
the problem is I don’t have value for the 2nd, 4th, 5th and 6th of the month. My idea was to force mongo to “create” void valid for the other days, like this:
const data = [
{ date: '2000-10-01', value: 50 },
{ date: '2000-10-02', value: 0 },
{ date: '2000-10-03', value: 12 },
{ date: '2000-10-04', value: 0 },
{ date: '2000-10-05', value: 0 },
{ date: '2000-10-06', value: 0 },
{ date: '2000-10-07', value: 112 },
];
How can I ask “aggregate” to fill the gap between significant dates with data with 0 as a value ?
Thanks
PS: I already did it by code in js but it looks heavy and ugly. I try to do it cleaner.