Fork me on GitHub

Validation

Before we get into the specifics of validation syntax, please keep the following rules in mind:

Built in validators

Mongoose has several built in validators.

Each of the validator links above provide more information about how to enable them as well as customize their associated error messages.

Custom validators

If the built-in validators aren't enough, validation can be completely tailored to suite your needs.

Custom validation is declared by passing a validation function and coinciding error message to your SchemaTypes validate method. Instructions for how to do so are available in the API docs.

Validation errors

Errors returned after failed validation contain an errors object holding the actual ValidatorErrors. Each ValidatorError has a type, path, and value property providing us with a little more error handling flexibility.

var toySchema = new Schema({
  color: String,
  name: String
});

var Toy = mongoose.model('Toy', toySchema);

Toy.schema.path('color').validate(function (value) {
  return /blue|green|white|red|orange|periwinkle/i.test(value);
}, 'Invalid color');

var toy = new Toy({ color: 'grease'});

toy.save(function (err) {
  // err is our ValidationError object
  // err.errors.color is a ValidatorError object
  
  console.log(err.errors.color.message) // prints 'Validator "Invalid color" failed for path color with value `grease`'
  console.log(String(err.errors.color)) // prints 'Validator "Invalid color" failed for path color with value `grease`'
  console.log(err.errors.color.type)  // prints "Invalid color"
  console.log(err.errors.color.path)  // prints "color"
  console.log(err.errors.color.value) // prints "grease"
  console.log(err.name) // prints "ValidationError"
  console.log(err.message) // prints "Validation failed"
});

After a validation error, the document will also have the same errors property available:

toy.errors.color.message === err.errors.color.message

Next Up

Now that we've covered validation, let's take a look at how you might handle advanced validation with Mongoose's middleware.