skip to Main Content
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


  1. 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 } }
    );
    
    Login or Signup to reply.
  2. 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 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search