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.

Custom validators

Custom validation is declared by passing a validation function and an error type to your SchemaTypes validate method. Read the API docs for details on custom validators, async validators, and more.

Validation errors

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

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

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

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

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

toy.save(function (err) {
  // err.errors.color is a ValidatorError object
  
  console.log(err.errors.color.message) // prints 'Validator "Invalid color" failed for path color'
  console.log(String(err.errors.color)) // prints 'Validator "Invalid color" failed for path color'
  console.log(err.errors.color.type) // prints "Invalid color"
  console.log(err.errors.color.path) // prints "color"
  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 Mongooses middleware.