Maria Jane Maria Jane - 5 months ago 49
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){
{email: subscriber_email},
{new: true})


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) {
      email: subscriber_email,
      credit:{$gte: 0}
    }, {
      $inc: {
        credit: price_per_use
    }, {
      new: true

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

Hope this can work for you