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

129
Vistas
How to keep decreasing value in mongo until is 0
singleObj = await Objects.findByIdAndUpdate({ _id: req.body.id, }, { $inc: { 'total_obj': -1, 'total_stuff': 1 }, }, { new: true })

The user clicks a button and the value of 'total_obj' gets decreased by one. The value doesn't have to be less than 0. I have tried to do this:

singleObj = await Objects.findByIdAndUpdate(
  { _id: req.body.id, "total_obj": { "$lt": 0 } },
  { "$set": { "total_obj": 0 } }
);

But this messes up every time I load the page and I have the values set to 0. I also added on the definition on the schema:

total_obj: {
    type: Number,
    required: true,
    min: 0
},
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I assume you meant that you don't want your value to be lesser than 0. You would need to use $gt operator and while you used $inc properly in the first findByIdAndUpdate you didn't use it in the second one.

Also, we are not looking only for id so we should use findOneAndUpdate instead.

singleObj = await Objects.findOneAndUpdate(
   { _id: req.body.id, "total_obj": { "$gt": 0 } },
   { $inc: { "total_obj": -1 } }
);
about 4 years ago · Juan Pablo Isaza Denunciar

0

Try to fetch the Objects instance first and update the value only if > 0:

const singleObj = await Objects.findById(req.body.id)
if (!singleObj) // Error, obj not found
if (singleObj.total_obj > 0) {
    singleObj.total_obj = singleObj.total_obj-1
    await singleObj.save()
} else { 
    // `total_obj` is already zero 
}
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