When we have been creating, editing, and saving data in our project, we have been using a callback function containing two parameters: an error object and the returned data object. So far we have generally been ignoring the error object and just been saving the data, for example:
user.save(function (err, user) { if(err){ console.log(err) } else { ...
It is in the err
object that we receive the Mongoose validation errors. The error object will contain a top-level message and name, and a collection of specific errors. Each of these errors give an individual message
, name
, path
, and type
object. A typical validation failure looks like the following when sent to the console:
{ message: 'Validation failed', name: 'ValidationError', errors: { email: { message: 'Validator "required" failed for path email', name: 'ValidatorError', path: 'email', type: 'required' }, name: { message: 'Validator "required" failed for path name', name: 'ValidatorError', path: 'name', type: 'required' } } }
Knowing the structure of the returned error object helps us to identify the exact reason for the validation failure and send a relevant error message to the user.
To output just a summary to the console, you could loop through the error objects with the following code snippet:
if(err){ Object.keys(err.errors).forEach(function(key) { var message = err.errors[key].message; console.log('Validation error for "%s": %s', key, message); }); }
This would result in a much more manageable output, which is as follows:
Validation error for "email": Validator "required" failed for path email Validation error for "name": Validator "required" failed for path name
3.134.118.95