$inc猫鼬,以防止负价值

$inc of mongoose to prevent negative value

本文关键字:inc 猫鼬      更新时间:2023-09-26

我下面的代码工作得很好,从用户在mongoose中使用$inc扣除信用(它适用于增量,这是伟大的),但是值可以变为负值,这是我不想要的,任何选项来防止这种情况?

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

你不能改变$inc的行为,但你可以在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);
}

现在,如果credit值大于zero,它将更新

希望这对你有用