Shriram Manoharan Shriram Manoharan - 1 year ago 125
Node.js Question

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:

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

Did I make any mistake with the code?

Answer Source

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.

For example:

User.findById(id, function(err, result) {
  if (err) return handleError(err);
  user.balance = -10; {
    if (err) return handleError(err);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download