Custom Casting

Mongoose 5.4.0 introduced several ways to configure SchemaTypes globally. One of these new features is the SchemaType.cast() function, which enables you to override Mongoose’s built-in casting.

For example, by default Mongoose will throw an error if you attempt to cast a string that contains a Japanese numeral to a number.

  1. const schema = new mongoose.Schema({
  2. age: Number
  3. });
  4. const Model = mongoose.model('Test', schema);
  5. const doc = new Model({ age: '二' });
  6. const err = doc.validateSync();
  7. // "Cast to Number failed for value "二" at path "age""
  8. err.message;

You can overwrite the default casting function for numbers to allow converting the string that contains the Japanese numeral “2” to a number as shown below.

  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. if (v === '二') {
  8. return 2;
  9. }
  10. return originalCast(v);
  11. });
  12. const schema = new mongoose.Schema({
  13. age: Number
  14. });
  15. const Model = mongoose.model('Test', schema);
  16. const doc = new Model({ age: '二' });
  17. const err = doc.validateSync();
  18. err; // null
  19. doc.age; // 2