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

238
Visualizações
How to count by Month in Nodejs?

My question is how to get total number of id's created per month. The below is my code fetching response from Mysql Db.

const dashboardOverview = async (req,res,next) => {
 var ordersPerMonth = await Orders.findAll({attributes:['od_id','od_created_date']});
     for(var i = 0; i < ordersPerMonth.length ; i++){
        let dataItem = {};
        for(const [key,value] of Object.entries(ordersPerMonth[i].dataValues)){
            dataItem[key.replace("od_","")] = value;
        }
        dataStore.push(dataItem);
    }
    console.log(dataStore)

    const arr = dataStore;
    console.log(arr)
    const counts = arr.reduce((m, { created_date }) => {
        // Create a key from the year and month, eg "2021-08"
        const key = created_date.substr(0, 7)
        
        // Increment the count for the key
        return m.set(key, (m.get(key) ?? 0) + 1)
      }, new Map())
      
      console.log(Object.fromEntries(counts))
}

Now in response I wanted monthname and total count of orders placed that month. For ex- [ January-21 : 23, February-21: 45......December-21: 56] But while using reduce() function I am getting type error:arr.reduce is not a function. I hope my query is clear.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This kind of result can be achieved by reducing your array to a map of month counts.

const formatter = new Intl.DateTimeFormat("en", {
  year: "2-digit",
  month: "long",
})

const formatKey = date => formatter.format(date).replace(" ", "-")

const dashboardOverview = async (req, res, next) => {
  const orders = await Orders.findAll({
    attributes: ["od_id", "od_created_date"]
  })

  const ordersPerMonth = orders.reduce((map, { od_created_date }) => {
    // assuming od_created_date is already a `Date` instance
    const key = formatKey(od_created_date).replace(" ", "-")

    return map.set(key, (map.get(key) ?? 0) + 1)
  }, new Map())

  const asObject = Object.fromEntries(ordersPerMonth)

  console.log(asObject)

  // and if you want to respond with JSON
  res.json(asObject)
}
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