Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
Adding Dates in Javascript

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 });
  })
);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda