intermediate
Validation
Validate document shape at the application boundary while keeping database constraints and API validation aligned.
Mongoose validators run on document paths before save or on configured update paths. They complement—but do not replace—API validation, authorization, and unique indexes.
email: {
type: String,
required: true,
validate: { validator: isEmail, message: 'invalid email' },
},
sku: { type: String, unique: true } // creates index, not a runtime validator
On interviews: explain required fields, custom validators, `runValidators` on updates, and why uniqueness needs an index plus application handling of duplicate key errors.
Common pitfalls: treating `unique: true` as a normal validator; updates bypassing validators; validation substituting for auth or transactional rules.
The trade-off is persistence-layer guards versus duplicated rules across API and database.
Checklist:
- Validate API input before persistence.
- Use indexes for uniqueness.
- Check update validator behavior.
- Handle duplicate key errors explicitly.