Understanding validation errors

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', ...

Get Mongoose for Application Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.