Facebook Pixel

How do I hash a password before saving in Mongoose?

Use a pre('save') hook. Check if the password field is modified with this.isModified('passwordHash'). If yes, hash with bcrypt and set this.passwordHash. Call next() to continue. Skip hashing otherwise (e.g., profile updates).

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Mongoose Middleware: pre and post Hooks Explained

Middleware functions that run before or after operations like save, validate, update. pre('save') runs before writing; post('save') runs after. Useful for hashing, normalizing, logging, and side effects.

Hooks use this to refer to the document being saved. Arrow functions do not bind this, so this would be undefined. Use regular functions (function(next) { ... }) instead.

Not by default. pre('save') runs on save; for updates you need to register hooks on findOneAndUpdate or updateOne explicitly. Be careful when updating passwords through these methods; hash them in the hook.

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.