Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda