Why CastError is throw before validate. So I cannot custom error message with CastError.
like:
birthday:{
type:Date
}
Schema.path('birthday').validate(function(date){
return _.isDate(date);
},'invalid birthday');
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锛烼hank you!!
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 CastError
, it's right there in the source code:
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 CastError
method is undocumented ( #4120).
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'
})
Most helpful comment
For those coming for finding a way customizing cast error message key. Here is an ugly, still working, way to do :
Then you can use it as a plugin :