自定义结构类型

¥Custom Schema Types

创建基本自定义结构类型

¥Creating a Basic Custom Schema Type

Mongoose 4.4.0 中的新功能:Mongoose 支持自定义类型。但是,在使用自定义类型之前,请注意自定义类型对于大多数用例来说都是多余的。你可以使用 自定义 getter/settervirtuals单个嵌入文档 完成大多数基本任务。

¥New in Mongoose 4.4.0: Mongoose supports custom types. Before you reach for a custom type, however, know that a custom type is overkill for most use cases. You can do most basic tasks with custom getters/setters, virtuals, and single embedded docs.

让我们看一个基本结构类型的示例:1 字节整数。要创建新的结构类型,需要继承 mongoose.SchemaType,并为 mongoose.Schema.Types 添加相应的属性。你需要实现的一种方法是 cast() 方法。

¥Let's take a look at an example of a basic schema type: a 1-byte integer. To create a new schema type, you need to inherit from mongoose.SchemaType and add the corresponding property to mongoose.Schema.Types. The one method you need to implement is the cast() method.

class Int8 extends mongoose.SchemaType {
  constructor(key, options) {
    super(key, options, 'Int8');
  }

  // `cast()` takes a parameter that can be anything. You need to
  // validate the provided `val` and throw a `CastError` if you
  // can't convert it.
  cast(val) {
    let _val = Number(val);
    if (isNaN(_val)) {
      throw new Error('Int8: ' + val + ' is not a number');
    }
    _val = Math.round(_val);
    if (_val < -0x80 || _val > 0x7F) {
      throw new Error('Int8: ' + val +
        ' is outside of the range of valid 8-bit ints');
    }
    return _val;
  }
}

// Don't forget to add `Int8` to the type registry
mongoose.Schema.Types.Int8 = Int8;

const testSchema = new Schema({ test: Int8 });
const Test = mongoose.model('CustomTypeExample', testSchema);

const t = new Test();
t.test = 'abc';
assert.ok(t.validateSync());
assert.equal(t.validateSync().errors['test'].name, 'CastError');
assert.equal(t.validateSync().errors['test'].message,
  'Cast to Int8 failed for value "abc" (type string) at path "test"');
assert.equal(t.validateSync().errors['test'].reason.message,
  'Int8: abc is not a number');