Mongoose Validation Errors
Handling Validation Errors in Node.js
Catching invalid Validators during update like name fields not meeting defined constrain (or) fields not part of predefined models
Below is code part of the users model update endpoint from task manager app :
User model has following allowed fields in endpoint is
const allowedUpdates = ["name", "email", "password", "age", "phone"];
and in order to check the allowed fields during an update operation, we need to request the Body from using Postman tool. In the above figure:
{
"age":25,
"mobile":"5432112345"
}
mobile is not a defined field in User model hence it should give the validation
Error: Task validation failed
but it will not show error as long as we catch and stop it. Same is with mobile.
In order to catch validation error. We can perform the following steps:
- Consider only keys from req.body data.
- List the allowed fields.
- Perform every() function on each field and by returning boolean(to track) true if entered field is part of the allowed list.
- if not part of the allowed list then sends 400 status code with error as invalid updates.
Conclusion
The goal here is to provide the user with much information as possible as to why things are not going as expected. Without Catching these validation Error user may get confused with the status code of 200 as success status. Using the above logic we can easily show the user with 400 status code as a bad request with error handling as :
{error: "Invalid Updates! ",}