Mongoose Validation: Your Schema's Built-in Guard

Mongoose validation is a guard at the application layer, ensuring data conforms to schema rules before hitting the database. Use it for required fields, lengths, and ranges. The unique option is for database indexes, not a Mongoose validation rule.
Why it exists
Databases have their own constraints, but validating at the application level is faster and provides better user feedback. Mongoose validation catches data integrity issues early, before a costly database roundtrip, by defining rules directly within your application's data model.
The mental model
Think of Mongoose validation as a set of bouncers for your data. Each field in your schema can have its own bouncer checking specific rules: Is this field present? Is this number high enough? Is this string on the list? If any bouncer rejects the data, the entire document is turned away before it can be saved. This happens automatically on every save() call.
How it works
You define validators inside your Mongoose Schema. Mongoose provides built-in validators like required, min/max for numbers, and minLength/maxLength/enum for strings. Validation is middleware that runs as the first pre('save') hook. If validation fails, the save() promise rejects with a validation error object, detailing which fields failed and why. You can also run validation manually using doc.validate() or doc.validateSync(). Validators, except for required, are skipped for undefined values.
When to use it
Use validation whenever you need to enforce the shape and integrity of your documents. It's perfect for ensuring a user has a name (required: true), a password meets a minimum length (minLength: 8), a product rating is between 1 and 5 (min: 1, max: 5), or a user role is one of a few specific options (enum: ['user', 'admin']).
When not to use it
The most common mistake is relying on the unique option as a validator. It is not. The unique option is a helper to build a unique index in MongoDB. While this index will cause a database error on duplicate entries, it does not trigger Mongoose's validation logic. You must handle the database-level error separately. Also, validation doesn't run by default on update operations like findOneAndUpdate(); it is primarily for document creation via save().
One canonical example
To create a breakfast model where eggs must be between 6 and 12, and drink must be 'Coffee' or 'Tea', you define it in the schema: const breakfastSchema = new Schema({ eggs: { type: Number, min: [6, 'Too few eggs'], max: 12 }, drink: { type: String, enum: ['Coffee', 'Tea'] } });. If you tried to save a document with eggs: 2, the .save() call would fail with a ValidationError, and the error message would be 'Too few eggs'.
Interview question
Which statement correctly distinguishes Mongoose validation from the 'unique' schema option?
- a.Mongoose validation ensures data types are correct, while the unique option prevents duplicate entries at the Mongoose schema level.
- b.Mongoose validation provides application-level data integrity checks, whereas the unique option configures a database index.Correct
- c.Mongoose validation runs automatically on findOneAndUpdate(), while the unique option only applies to save() calls.
- d.Both Mongoose validation and the unique option are part of the pre('save') hook middleware.
Why? this is the answer
Mongoose validation is described as an application-layer guard for data integrity, while the unique option is explicitly stated to be a helper for building a database index, not a Mongoose validation rule. The unique option's enforcement happens at the database level, not as part of Mongoose's validation middleware.
Just read this? Test yourself on what you have been reading.
Read the original → mongoosejs.com
- #mongoose
- #nodejs
- #database
- #validation
You just looked this up. Could you explain it out loud?
That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.
See open roles