Maria Jane Maria Jane - 1 month ago 19
Node.js Question

$inc of mongoose to prevent negative value

My below code work just fine deducting credit (it work for increment which is great) from user using $inc in mongoose, but the value can become negative which is what I don't want, any option to prevent that?

module.exports.deduct_credit = function(subscriber_email,callback){
Users.findOneAndUpdate(
{email: subscriber_email},
{$inc:{credit:price_per_use}},
{new: true})
.exec(callback);
}

Answer

You can't change the $inc behaviour but you can do a checkpoint to stop it after zero

module.exports.deduct_credit = function(subscriber_email, callback) {
  Users.findOneAndUpdate({
      email: subscriber_email,
      credit:{$gte: 0}
    }, {
      $inc: {
        credit: price_per_use
      }
    }, {
      new: true
    })
    .exec(callback);
}

Now it will update if the credit value is greater that zero

Hope this can work for you

Comments