自定义转换

Mongoose 5.4.0 引入了 几种在全局范围内配置 SchemaTypes 的方法。其中一项新功能是 SchemaType.cast() 函数,它允许您覆盖 Mongoose 的内置转换功能。

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

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”的字符串转换为数字,如下所示。

// 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