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
},
2
Answers
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 firstfindByIdAndUpdate
you didn’t use it in the second one.Also, we are not looking only for id so we should use
findOneAndUpdate
instead.Try to fetch the
Objects
instance first and update the value only if> 0
: