定制铸造

¥Custom Casting

Mongoose 5.4.0 介绍了 全局配置 SchemaType 的几种方法。这些新功能之一是 SchemaType.cast() function,它使你能够覆盖 Mongoose 的内置转换。

¥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.

例如,默认情况下,如果你尝试将包含日语数字的字符串转换为数字,Mongoose 会抛出错误。

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

const schema = new mongoose.Schema({
  age: Number
});
const Model = mongoose.model('Test', schema);

const doc = new Model({ age: '二' });
const err = doc.validateSync();
// "Cast to Number failed for value "二" at path "age""
err.message;

你可以覆盖数字的默认转换函数,以允许将包含日语数字 "2" 的字符串转换为数字,如下所示。

¥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.

// 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 => {
  if (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