Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Min validation not working in Mongoose

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

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

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.

My update query:

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

Did I make any mistake with the code?

like image 358
Shriram Manoharan Avatar asked Oct 26 '25 12:10

Shriram Manoharan


1 Answers

By default mongoose does not validate on an update call, however there is an option for this. Look at the mongoose documentation: http://mongoosejs.com/docs/validation.html (Update Validators)

var opts = { runValidators: true };
Toy.update({}, { color: 'bacon' }, opts, function (err) {
  assert.equal(err.errors.color.message,
    'Invalid color');
});
like image 77
Camo Avatar answered Oct 29 '25 01:10

Camo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!