Catch the error in your handler. Check err.code === 11000 (MongoDB duplicate key error). Return 409 with a clear message instead of letting the error handler send a 500.
Common Mongoose Mistakes (and How to Avoid Them)
How do I handle duplicate key errors in Mongoose?
The answer
More FAQs in Common Mongoose Mistakes (and How to Avoid Them)
No validation on updates, plain-text passwords, returning passwordHash, no indexes on hot queries, embedding unbounded arrays, N+1 queries, not handling duplicate key errors, no pagination, no .lean() for read-only queries, sync calls, mixing validation with logic, and no timestamps.
Mark the field with select: false in the schema. It is excluded from find queries by default. Use .select('+passwordHash') only when needed (e.g., for login).
Mongoose runs validation on .save() and .create() but not on findByIdAndUpdate or updateOne by default. Pass { runValidators: true, new: true } on every update to enforce validation.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.