matteodelabre / mongoose-beautiful-unique-validation

Plugin for Mongoose that turns duplicate errors into regular Mongoose validation errors
MIT License
117 stars 38 forks source link

Add error code and array of duplicates in beautified error #34

Open Igor-Lopes opened 7 years ago

Igor-Lopes commented 7 years ago

It would be easier to have the error code (E11000 or E11001) in the beautified error JSON, as well, an array of duplicates fields right away. In my Express App, in every Insert or update I try to catch mongoose errors. If it's a duplicate error, I have to give the duplicate fields in the response, otherwise, I throw a 500 error and log de request. Here's a beautified error example with the changes:

{
    "errors": {
        "email": {
            "message": "Validator failed for path `email` with value `user@email.com`",
            "name": "ValidatorError",
            "properties": {
                "type": "Duplicate value",
                "path": "email",
                "value": "user@email.com"
            },
            "kind": "Duplicate value",
            "path": "email",
            "value": "user@email.com"
        }
    },
    "message": "Validation failed",
    "name": "ValidationError",
    "code": 11000,
    "fields": [
        "email"
    ]
}
matteodelabre commented 7 years ago

Hello @Igor-Lopes, thanks for your contribution, and sorry for the delay in answering! I totally agree on the usefulness of a code attribute. However, the data in your proposed fields attribute can easily be computed using Object.keys(err.errors).