I am trying to turn the error messages of Validation from Mongoose into readable data for Vee Validate.
In this case I am using mongoose unique validator to enforce unique emails. I get the errors of this in this email example and get the following:
{
email: {
kind: "unique",
path: "email",
message: "Email address seems to already exist",
path: "email",
type: "unique",
value: "[email protected]",
}
}
I return this as the json error data where I add it to Vee Validate using setErrors
So in this case I want the object to turn into:
{
email: ['Email address seems to already exist']
}
So I want to map one object to another while still allowing more than one erroring field to be exist in case more server side validation existed that frontend couldn't cover.
I am open to solutions that are changing the validation error object itself but I haven't found anything useful with moongoose validation yet.
If you want to convert {email: {message: "email error"}, password: {message: "password error"}}
to {email: ["email error"], password: ["password error"]}
You can use reduce function (with Object.keys to convert to array):
const data = {
email: {
message: "Inavlid email"
},
username: {
message: "Inavlid username"
},
password: {
message: "Inavlid password"
}
};
const transformed = Object.keys(data).reduce((acc, k) => {
return {
[k]: [data[k].message],
...acc
};
}, {});
console.log(transformed)
// transformed = {email: ["Invalid email"], username: ["Invalid username"], password: ["Invalid password"]};