Mongoose validation – the basics
In Mongoose, validation is set at the schema level. Remember how in our userSchema
we have this for the email
field:
email: { type: String, unique: true }
The unique: true
part is a type of validation that Mongoose passes directly through to MongoDB. The other types of validation we are about to look at are set in the same place, but are handled by Mongoose before it goes anywhere near the database; unless of course, you have a type of validation where you specifically choose to check against something in the database.
Default validators
Mongoose provides some common validators to get us started. We'll look at them in this chapter. Some of these are for specific SchemaTypes, which we'll get to know in a moment, but there is one that can be used on all SchemaTypes.
All SchemaTypes
There is one validator that can be used by any SchemaType, named required. This will return a validation error if no data is given to a data object with this property. It is super-easy...