'How to clean up mongoose validation errors

I am using mongoose for validation, and I want to pass the results back to the client. The JSON blob that mongoose gives for errors is almost exactly what I need, but it has some extra stuff:

errors: 
 { username: 
    { [ValidatorError: Path `username` is required.]
      properties: [Object],
      message: 'Path `username` is required.',
      name: 'ValidatorError',
      kind: 'required',
      path: 'username',
      value: undefined } } }

The username.properties field is unecessary for the client. I know I can do delete username.properties, but is there a nicer way to clean up the JSON?



Solution 1:[1]

Use the lodash library

var _ = require('lodash');

yourMongooseError = _.mapValues(yourMongooseError, function(field) {
  return _.omit(field, ['properties']); // add any other props that you want to remove from each field
});

Solution 2:[2]

Object.entries(err.errors).map((error: any) => error[1].message).join()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yuri Zarubin
Solution 2 Lalit