Facebook Pixel

How do you handle async errors with Mongoose?

Wrap async handlers with asyncHandler that catches promise rejections and calls next(err). Catch duplicate key errors (err.code === 11000) and return 409. Catch ValidationError and return 400 with field list.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Mongoose Models Interview Questions and Answers

A schema defines the shape of a document (fields, types, validation). A model is a constructor compiled from a schema; it is what you use to query the database. Schema is the blueprint; model is the database interface.

Use a pre('save') hook. Check this.isModified('passwordHash'). If yes, hash with bcrypt. Mark the field with select: false so it is not returned by default. This keeps hashing logic close to the data.

Add a unique index on the field. Catch err.code === 11000 in your handler and return 409 with a clear message. The unique index enforces uniqueness; the catch gives clean UX instead of a 500.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.