验证

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

  • Validation is defined in the SchemaType
  • Validation is an internal piece of middleware
  • Validation occurs when a document attempts to be saved, after defaults have been applied
  • Validation is asynchronously recursive; when you call Model#save, sub-document validation is executed as well. If an error occurs, your Model#save callback receives it
  • Validation supports complete customization

内置验证器

Mongoose has several built in validators.

  • All SchemaTypes have the built in required validator.
  • Numbers have min and max validators.
  • Strings have enum and match validators.

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

自定义验证器

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

results matching ""

    No results matching ""