Custom Casting
// Calling `cast()` on a class that inherits from `SchemaType` returns the
// current casting function.
const originalCast = mongoose.Number.cast();
// Calling `cast()` with a function sets the current function used to
// cast a given schema type, in this cast Numbers.
mongoose.Number.cast(v => {
return 2;
}
return originalCast(v);
});
const schema = new mongoose.Schema({
age: Number
const Model = mongoose.model('Test', schema);
const doc = new Model({ age: '二' });
const err = doc.validateSync();
err; // null
doc.age; // 2