I'm pretty new to javascript, and I'm creating a dashboard for an e-commerce website that I am working on. and I'm trying to show data for all dates starting with the date of the first order made. MongoDB of course only shows data for the dates that the order were made, so I'm trying to add missing dates to my MongoDB data using javascript. I'm having some trouble doing this and I would really appreciate any advice or help on how to get this to work.
Thank you!
OrderRouter.js
import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import Order from '../models/orderModel.js';
import User from '../models/userModel.js';
import Product from '../models/productModel.js';
orderRouter.get(
'/summary',
isAuth,
isAdmin,
expressAsyncHandler(async (req, res) => {
const dailySales = await Order.aggregate([
{
$group: {
_id: { $dateToString: { format: '%m-%d-%Y', date: '$createdAt' } },
orders: { $sum: 1 },
sales: { $sum: '$totalPrice' },
},
},
{ $sort: { _id: 1 } },
]);
const datesArray = getDates(startDate, endDate)
for(date in datesArray){
isInArray = true;
for (day in dailySales){
if (day._id === date){
isInArray = true;
}
}
if (isInArray = false){
dailySales.push({ "_id":"date", "orders":0, "sales":0})
}
}
res.send({dailySales });
})
);
I'm not sure how you wrote getDates, but it'll be much easier to work with date objects, like so:
const finalResults = [];
const ONE_DAY = 1000 * 60 * 60 * 24;
if (dailySales.length) {
let currDate = new Date(dailySales[0]._id);
const endDate = new Date(dailySales[dailySales.length - 1]._id);
while (currDate <= endDate) {
if (currDate.getTime() === new Date(dailySales[0]._id).getTime()) {
finalResults.push(dailySales[0])
dailySales.shift();
} else {
const day = currDate.getUTCDate();
const month = currDate.getMonth();
finalResults.push({
_id: `${month < 10 ? "0" : ''}${month}-${day < 10 ? '0' : ''}${day}-${currDate.getFullYear()}`,
orders: 0,
sales: 0
})
}
currDate = new Date(currDate.getTime() + ONE_DAY)
}
}
Now we iterate day by day, if it exists then we just add the existing obj, if it doesn't we generate a new document and continue the loop.