How to add days in javascript to fill in missing dates from data

Viewed 148

I'm pretty new to javascript. I'm trying to graph orders by the dates that they were made. I want the graph to contain the days in-between those orders with orders for those dates as 0. How would I add these missing dates in javascript? In my backend, I'm using mongodb aggregate.

const dailyOrders = await Order.aggregate([
     {
      $group: {
        _id: { $dateToString: { format: '%m-%d-%Y', date: '$createdAt' } },
        orders: { $sum: 1 },
      },
    },
    { $sort: { _id: 1 } },
  ]);

Would I have to create a const and add it to createdAt? I would really appreciate any help or guidance on how to do this. Thank you!

1 Answers

You can make mongoDB to return javascript dates not strings. You can use $dateFromString (or you can return strings, and convert them to dates in javascript)

documents=[doc1(has_the_start_date) doc2 ......docn(has_the_end_date)]

An then you make an array with 1 document for each day, if you have doc for that date in documents you take it from there, else you create an empty doc with that date.

var docIndex=0;
var temp_date=startDate;
var documents_all_dates=[];

while(date<=endDate)
{
  //if i have a document with that date,find out how to compare date day in js
  if(documents[docIndex]["date"] equal temp_date)
  { 
    documents_all_dates.push(documents[docIndex]);
    docIndex++;
  }
  else
  {
    newDoc=...create_document_with_the_date...
    documents_all_dates.push(newDoc);
  }
  temp_date.setDate(temp_date.getDate() + 1);
}

Answer is not complete but it might help you.

Related