Why should I not use arrow functions in Mongoose hooks?
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.
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.
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).
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
