Based on my own knowledge, you can do almost every validation in mongoose schema that you can do with express-validator. So pls can I just use mongoose or there are situation that I will need to use express-validator too even if I only create new documents
Indeed, you can do almost every validation in your mongoose schema like you can do using express-validator. Mongoose now supports validation on update
as well, so you are good to go.
Let me point out two cases:
If the validation logic is simple and small, there is no problem
about mongoose validation. But in case of complex validation rules
and multiple fields, then express-validator may be better choice.
If the mongoose built-in validators are not enough for your validation logic, you have to create custom validators. You will have to add much more lines of code, ending up with a too big mongoose model file.
As far I am concerned, i want model js files as clean as possible. Express-validator, which is a wrapper for validator.js offers validators (e.g. isAlphanumeric, isEmail and much more) which can save you from a lot of lines of code. Thus you keep your validation logic in separated files, and have your code more clean and organised.
The other point is about the code execution flow.
Express-validator is a validation middleware. When you send a form through a post request, you can run the validation logic and in case of any error you return error messages to client, without reaching the controller or service code.
Again, to my perspective is a bad practice to run controller or other service code (depending your architecture), with data send from client without being validated or sanitized. Using Express-validator, when code execution flow reaches the controller logic, that means the data you are going to insert to database, are well checked and sanitized.
Without using any validation middleware, you have to run all the controller logic, and wait for possible validation error, only when flow reaches the mongoose save or update method. Imagine your controller includes a dozen service functions. Why run all this logic if it is to cancel it due to invalid data?
In conclusion, both methods can satisfy your validation rules. In my opinion, go with Exspress-validator for cleaner and more organised code, as well as for better and more safe code execution flow.