New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
I want to hook cast error with custom error message. #3162
Comments
Unfortunately not that I know of. Casting is deeply ingrained into mongoose and always executes before any validation, so I don't think there's a way to set custom cast errors. But definitely something to consider for the future. |
+1 |
There is a way to set a custom value for a https://github.com/Automattic/mongoose/blob/master/lib/error/cast.js#L16 It's just this value appears to be ignored. It doesn't help that that the We are working on mongoose-geojson-schema. It adds schema and validation support for GeoJSON elements to Mongoose. When the GeoJSON is not valid, we would like to tell people why. Right now the error is always "failure to cast", which is frustrating because there are several ways GeoJSON validation can fail and the current diagnostic doesn't provide a clue as to /why/ the validation is failing. |
For those coming for finding a way customizing cast error message key. Here is an ugly, still working, way to do : const castWithMessageKey = function(schema, options = {}) {
schema.post('validate', function(error, doc, next) {
Object.values(error.errors)
.filter(fieldError => fieldError.name === 'CastError')
.forEach(fieldError => {
fieldError.message = options.messageKey || 'error.common.cast';
});
next(error);
});
};
export default castWithMessageKey; Then you can use it as a plugin : import castWithMessageKey from './PATH/TO/castWithMessageKey.js'
...
mySchema.plugin(castWithMessageKey)
// or with custom message override :
mySchema.plugin(castWithMessageKey, {
messageKey : 'foobar'
}) |
With #13608, you'll be able to do the following: new Schema({
birthday: {
type: Date,
cast: 'invalid birthday'
}
}); or: Schema.path('birthday').castFunction('invalid birthday'); |
feat: support generating custom cast error message with a function
Why CastError is throw before validate. So I cannot custom error message with CastError.
like:
And when I set birthday to a invalid date,then call save method.
But,'invalid birthday' hook is after mongoose build-in CastError , so I cannot get the error with message 'invalid birthday'.
Has any method to do it?Thank you!!
The text was updated successfully, but these errors were encountered: