Remember the following points before you begin
- validation defined in SchemaType
- Validation is an internal middleware
- Validation occurs before document is to be save
- Validation does not occur on null values unless the corresponding field is added with required validator
- You can customize the validator
Built-in Validator
- All SchemaType have required validators.
- Number has min and Max validators
- String has enum and match validator
Custom Validator
Ensure that the value is Somethingfunction validator (val) {return val = = "Something";} New Schema ({name:{type:string, validate:validator}});//Custom error message var custom =[validator, ' {PATH} does not equal something ' ];new Schema ({name:{type:string, validate:custome});//Add multiple validators at once var many = [ {validator:validator, msg: ' Uh oh '},< C3/>{validator:anothervalidator, msg: ' Failed '}];new schema ({name: {type:string, validate:many});//orvar schema = new Schema ({name: ' string '}); Schema.path (' name '). Validate (Validator, "{path} {VALUE}");
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 colo R "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)//P Rints "ValidationError" Console.log (err.message)//prints "Validation failed"});
When a validation error occurs, document General has a Erros attribute:
Toy.errors.color.message = = Err.errors.color.message
Mongoose Guide-Validation