Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
Cómo mantener el valor decreciente en mongo hasta que sea 0
singleObj = await Objects.findByIdAndUpdate({ _id: req.body.id, }, { $inc: { 'total_obj': -1, 'total_stuff': 1 }, }, { new: true })

El usuario hace clic en un botón y el valor de 'total_obj' se reduce en uno. El valor no tiene que ser inferior a 0. He intentado hacer esto:

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

Pero esto se estropea cada vez que cargo la página y tengo los valores establecidos en 0. También agregué la definición en el esquema:

 total_obj: { type: Number, required: true, min: 0 },
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Supongo que quiso decir que no quiere que su valor sea menor que 0. Necesitaría usar el operador $gt y, aunque usó $inc correctamente en el primer findByIdAndUpdate , no lo usó en el segundo.

Además, no estamos buscando solo la identificación, por lo que deberíamos usar findOneAndUpdate en su lugar.

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

0

Intente buscar primero la instancia de Objects y actualice el valor solo si > 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!