mongoose4.5中文教程
  • Introduction
  • Mongoose
  • guide
    • 模式(schemas)
      • 模式类型(types)
      • 自定义类型(custom)
    • 模型(models)
    • 文档(documents)
      • 子文档(sub docs)
      • 默认值(defaults)
    • 查询(queries)
    • 验证(validation)
    • 中间件(middleware)
    • 联表(population)
    • 连接(connections)
    • 插件(plugins)
    • 承诺(promises)
    • 鉴频器(discriminators)
    • 贡献
    • ES2015 整合
    • 浏览器中的schemas
    • 自定义schema类型
    • MongoDB版本兼容性
    • 3.6 发布说明
    • 3.8 发布说明
    • 4.0 发布说明
  • API 文档
Powered by GitBook
On this page

Was this helpful?

  1. guide

自定义schema类型

Previous浏览器中的schemasNextMongoDB版本兼容性

Last updated 6 years ago

Was this helpful?

原文: 翻译:小虾米(QQ:509129)

创建一个基本的自定义模式类型

在Mongoose 4.4.0的新特性:Mongoose支持自定义类型。在你到达一个自定义的类型之前,然而,知道一个自定义类型是大多数情况下矫枉过正。你可以用最基本的任务采用,,和。

让我们看看一个基本模式类型例子:一个字节的整数。创建一个新的模式类型,你需要继承mongoose.SchemaType和添加相应的属性到mongoose.Schema.Types。你需要实现一个方法是cast()方法。

function Int8(key, options) {
      mongoose.SchemaType.call(this, key, options, 'Int8');
    }
    Int8.prototype = Object.create(mongoose.SchemaType.prototype);

    // `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.
    Int8.prototype.cast = function(val) {
      var _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;

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

    var 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" at path "test"');
    assert.equal(t.validateSync().errors['test'].reason.message,
      'Int8: abc is not a number');
Creating a Basic Custom Schema Type
自定义的getters/setters
虚函数
单一的嵌入式文档