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

276
Visualizações
After finding the right document, how do I query the object with the right date and update it in mongoose?

I am trying to create a heatmap using react-d3-heatmap and it needs data as [{date: Date, count: Number}].

This is my model.

const HeatMapSchema = new mongoose.Schema({
    user: {type: mongoose.Schema.ObjectId, ref: 'User'},
    data: [{
        date: { 
            type: Date,
            default: Date.now
        },
        count: { 
            type: Number,
            default: 0
         },
    }]
})

I have tried a bunch of different ways to query the document that pertains to the correct user and then go into the data to query the date and increment the count. I installed moment.js to help query the date. Can you help me find the model matching the user and update the count for that day within the data object? Thanks

import HeatMap from '../models/heatmap.model'
import errorHandler from './../helpers/dbErrorHandler'
import moment from 'moment'    
const addDate = async (req, res) => {
      const id = '60e88ceaa331a63d2c9523fc'
      const today = moment().startOf('day')
      try {
        let data = await HeatMap
          .find({user: id})
          .updateOne({data: {date: {$gte: today.toDate(), $lte: moment(today).endOf('day').toDate()}}}, {count: 1})
        res.json(data)
      } catch (err) {
        return res.status(400).json({
          error: errorHandler.getErrorMessage(err)
        })
      }
    }

export default {
    create,
    getHeatMapData,
    addDate  
}

found a way.

const addDate = async (req, res) => {
  const id = '60e88ceaa331a63d2c9523fc'
  const today = moment().startOf('day')
  try {
    const query = { user: id, "data.date": {
      $gte: today.toDate(),
      $lte: moment(today).endOf('day').toDate()}
    }
    const updateDocument = {
      $inc: { "data.$.count": 1 }
    };
    let data = await HeatMap.find({$and: [
      {user: id}, {"data": {$gte: today.toDate()}}
    ]})
    if (data.length === 0) {
      await HeatMap.updateOne({user: id}, {"$push": {"data": {'count': 0}}})
    } else {
      data = await HeatMap.updateOne(query, updateDocument)
    }
    res.json(data)
  } catch (err) {
    return res.status(400).json({
      error: errorHandler.getErrorMessage(err)
    })
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

in updateOne use this :

updateOne({$set:{"data.$[elem].count": 1}},
{$arrayFilters:[{"elem.date": {$gte: today.toDate(), $lte: moment(today).endOf('day').toDate()}}]})
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