I am pretty new to Node backend development, since I am coming from frontend. I am developing an http api using Express, Mongo, Mongoose and Joi for input validation.
I am using both Mongoose and Joi schema validation, the latter just in particular cases, such as post/put/patch routes.
Using an "unique" rule in Mongoose schema for email field I've stumbled upon the following issue: Mongoose error responses are quite a lot different from Joi ones. As you can imagine, consistent responses should be preferred to avoid complicated data parsing on the frontend to show errors in the UI.
This is an example of Mongoose error response for unique email:
{
"errors": {
"email": {
"message": "Error, expected 'email' to be unique. Value: '[email protected]'",
"name": "ValidatorError",
"properties": {
"message": "Error, expected 'email' to be unique. Value: '[email protected]'",
"type": "unique",
"path": "email",
"value": "[email protected]"
},
"kind": "unique",
"path": "email",
"value": "[email protected]"
}
},
"_message": "Author validation failed",
"message": "Author validation failed: email: Error, expected 'email' to be unique. Value: '[email protected]'",
"name": "ValidationError"
}
while this is an example of Joi error response for wrong password:
{
"isJoi": true,
"name": "ValidationError",
"details": [
{
"message": "\"password\" with value \"3\" fails to match the required pattern: /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,32}$/",
"path": [
"password"
],
"type": "string.regex.base",
"context": {
"pattern": {},
"value": "3",
"key": "password",
"label": "password"
}
}
],
"_object": {
"username": "thequickbrownfox",
"first_name": "The Quick",
"last_name": "Brown Fox",
"email": "[email protected]",
"password": "3"
}
}
Please note that I am also using Mongoose Unique Validator to get Mongoose unique error messages instead of the default E11000 Mongo error which is quite speechless. Is there any way to get similar error responses in suchlike use cases? Thanks.