Custom Casting

    1. // Calling `cast()` on a class that inherits from `SchemaType` returns the
    2. // current casting function.
    3. const originalCast = mongoose.Number.cast();
    4. // Calling `cast()` with a function sets the current function used to
    5. // cast a given schema type, in this cast Numbers.
    6. mongoose.Number.cast(v => {
    7. return 2;
    8. }
    9. return originalCast(v);
    10. });
    11. const schema = new mongoose.Schema({
    12. age: Number
    13. const Model = mongoose.model('Test', schema);
    14. const doc = new Model({ age: '二' });
    15. const err = doc.validateSync();
    16. err; // null
    17. doc.age; // 2