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

127
Views
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 answers
Answer question

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 Report

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