最小验证在猫鼬中不起作用 [英] Min validation not working in Mongoose

查看:67
本文介绍了最小验证在猫鼬中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个架构,其中声明了余额字段,如下所示

I have a Schema in which the balance field is declared as shown below

balance: {
    type: Number,
    min: 0,
    default: 30
}

我将0设置为最小值,以便余额不会为负值.但是,当我通过更新查询减少余额值时,余额证明是负值.

I have set 0 as minimum value so that the balance would not be a negative value. But when I decrement the balance value through update query, balance turns out to be a negative value.

我的更新查询:

User.update({
    _id: mongoose.Types.ObjectId(id)
}, {
    $inc: {
        balance: -10
    }
}, function(error, result) {
    // code
});

代码有误吗?

推荐答案

猫鼬验证是一种内部中间件,在更新时不会调用它;如果要在更新时强制执行验证,则应该找到文档,更新属性并保存.

Mongoose validation is an internal middleware which is not called on update; if you want to enforce validations on update, you should find the document, update the attributes, and save it.

例如:

User.findById(id, function(err, result) {
  if (err) return handleError(err);
  user.balance = -10;
  user.save(function(err) {
    if (err) return handleError(err);
    ...
  });
});

这篇关于最小验证在猫鼬中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆