I need to extract documents from the last 7 days stored in my Mongo Database.
I have successfully retrieved data in the desired format, where specific dates and the number of tickets created on those dates are returned:
{
"datesUsed": {
"startDate": "2022-04-02T14:42:14.223Z",
"endDate": "2022-04-09T14:42:14.223Z"
},
"data": [
{
"date": "02/04/2022",
"numOfTickets": 1
},
{
"date": "03/04/2022",
"numOfTickets": 1
},
{
"date": "04/04/2022",
"numOfTickets": 2
},
{
"date": "06/04/2022",
"numOfTickets": 1
},
{
"date": "07/04/2022",
"numOfTickets": 1
},
{
"date": "08/04/2022",
"numOfTickets": 2
},
{
"date": "09/04/2022",
"numOfTickets": 1
}
]
}
The issue arises when Mongo only returns data for days with documents created, leaving out days like 05/04/2022 when no document was created.
My goal is to include another JSON object that accounts for these missing days as well:
{
"date": "05/04/2022",
"numOfTickets": 0
}
This is what I currently have implemented:
const companyId = req.query.companyId;
let dates = [];
const data = [];
// Last 7 days
const endDate = new Date();
const startDate = new Date(Date.now() - 604800000);
// Retrieve tickets from the past 7 days
const allCompanyTickets = await ticketModel
.find({
company_id: companyId,
createdAt: { $gte: new Date(startDate), $lte: new Date(endDate) },
})
.sort({ createdAt: 1 });
console.log(allCompanyTickets)
// Add them to an array
allCompanyTickets.forEach((ticket) => {
dates.push(ticket.createdAt.toLocaleDateString());
});
// Calculate occurrences of days in the dates array
function countOccurrences(arr) {
return arr.reduce(function (a, b) {
a[b] = a[b] + 1 || 1;
return a;
}, []);
}
// Construct an object based on the calculated data
const datesOrdered = countOccurrences(dates);
// Assign keys to the data and push it to a new array
for (let key in datesOrdered) {
const tempObj = { date: key, numOfTickets: datesOrdered[key] };
data.push(tempObj);
}
res.status(200).json({ datesUsed: { startDate, endDate }, data: data });