Facebook Pixel

Why keep business logic out of Mongoose hooks?

Hooks are for data-related concerns (hashing, normalizing, logging). Business logic (emails, payments) in hooks becomes a tangled web that is hard to test and reason about. Put it in services or controllers 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).

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.

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.