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

275
Vistas
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 Respuestas
Responde la pregunta

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 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