Facebook Pixel

Should I put business logic in Mongoose validators?

No. Validators should check data shape (user must be 18). Business rules (user cannot signup if they have unpaid invoices) belong in a service. Mixing them makes validators hard to test and reason about.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Schema Validation in Mongoose: Best Practices

Use built-in validators (required, min, max, minlength, maxlength, enum, match). Add custom validators with the validate property for complex rules. Use runValidators: true on updates. Combine with Zod at the middleware layer for defense in depth.

Mongoose runs validation on .save() and .create() but not on findByIdAndUpdate or updateOne by default. Pass { runValidators: true, new: true } on every update to enforce validation.

No. It is an index. It does not produce a ValidationError. It produces a 11000 duplicate key error. Catch it in your handler: if (err.code === 11000) return res.status(409).json({ error: 'Email already in use' }).

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.