Maria Jane Maria Jane - 1 year ago 116
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})

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download