Q11: How does built-in and custom schema validation work in Mongoose?
Mongoose validates documents against schema constraints prior to saving:
- Built-in:
required,min,max,enum,minLength,match(regex). - Custom Validator: Defined using the
validatekey taking a validator function or regex alongside a custom error message string.
Custom Mongoose Schema Validator
const userSchema = new mongoose.Schema({
phone: {
type: String,
validate: {
validator: function(v) {
return /\d{3}-\d{3}-\d{4}/.test(v);
},
message: props => `${props.value} is not a valid phone number!`
},
required: [true, 'User phone number required']
}
});💡 Validates input phone strings against regex patterns before writing to the database.
Key Takeaways
- Validation runs automatically on
doc.save(). - Can enable validation on updates via
{ runValidators: true }option.
Knowledge Check
Does Model.findByIdAndUpdate() trigger schema validators by default in Mongoose?