0

I'm running Mongoose 3.8.8 and am having trouble trying to get it to enforce the built-in validation rules against a property of my model.

I have the following:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

/**
 * Drink Schema
 */
var DrinkSchema = new Schema({
    name: {type: String, required: "{PATH} is required."},
    description: String,
    sku: {type: String, required: "{PATH} is required."},
    contains: String,
    count: { type: Number, min: 0 }
});

mongoose.model('Drink', DrinkSchema);

When I insert a drink with a negative count (via Drink.update({sku:sku}, {name:name, count: -1}, {upsert:true}, callback);) I am met with success. Querying the database confirms that the document insertion was permitted.

I'm new to this ecosystem, so any advice would be appreciated. Thanks!

Community
  • 1
  • 1
Mr. S
  • 1,469
  • 2
  • 15
  • 27

1 Answers1

1

Validation is an internal middleware which doesn't get called on Model.update. If you want validations to run on update, you need the find the document, update the attributes and save it. Like in the documentation:

Tank.findById(id, function (err, tank) {
  if (err) return handleError(err);

  tank.size = 'large';
  tank.save(function (err) {
    if (err) return handleError(err);
    res.send(tank);
  });
});
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94