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

Punitkumar Harsur
Webtips

--

Below is code part of the users model update endpoint from task manager app :

Catching Validation Errors
Users model update endpoint

User model has following allowed fields in endpoint is

const allowedUpdates = ["name", "email", "password", "age", "phone"];
postman to test update

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:

  1. Consider only keys from req.body data.
  2. List the allowed fields.
  3. Perform every() function on each field and by returning boolean(to track) true if entered field is part of the allowed list.
  4. if not part of the allowed list then sends 400 status code with error as invalid updates.
catching Validation errors

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! ",}

--

--

Punitkumar Harsur
Webtips

Data science SME. Hustler, Content creator, Photography Enthusiast. LinkedIn: www.linkedin.com/in/punityh