Shriram Manoharan
Shriram Manoharan

Reputation: 585

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?

Upvotes: 4

Views: 3525

Answers (4)

David Bova
David Bova

Reputation: 41

None of these answers actually answer the question.

I came up against this and even with the runValidators flag - Mongoose will not validate on some operations. As below

https://mongoosejs.com/docs/validation.html#update-validators-only-run-for-some-operations

One final detail worth noting: update validators only run on the following update operators:

$set

$unset

$push (>= 4.8.0)

$addToSet (>= 4.8.0)

$pull (>= 4.12.0)

$pullAll (>= 4.12.0)

For instance, the below update will succeed, regardless of the value of number, because update validators ignore $inc.

Upvotes: 4

Arian Acosta
Arian Acosta

Reputation: 6827

Enabling validation on update (which is disabled by default) using findByIdAndUpdate would look like this:

User.findByIdAndUpdate(id, {
  $set: attributes,
}, {
  new: true,
  runValidators: true,
})
.then((user) => {
  if (!user) {
    // user not found
  }

  console.log(user);
})
.catch(e => console.log(e));

Upvotes: 1

Camo
Camo

Reputation: 1180

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');
});

Upvotes: 5

MarcoS
MarcoS

Reputation: 17721

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;
  user.save(function(err) {
    if (err) return handleError(err);
    ...
  });
});

Upvotes: 2

Related Questions