Facebook Pixel

What is .lean() in Mongoose and when should I use it?

Returns plain JS objects instead of full Mongoose documents. Faster and uses less memory. Use for read-only queries where you only need to send JSON. Do not use it if you need to call instance methods or save the document.

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.