# 自定义类型（custom）

> 原文：[Creating a Basic Custom Schema Type](http://mongoosejs.com/docs/customschematypes.html)\
> 翻译：小虾米（QQ:509129）

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

Mongoose 4.4.0的新特征：Mongoose支持自定义类型。在你达到一个自定义的类型，然而，知道一个自定义的类型是过度对大多数用例。你可以用最基本的任务 [custom getters/setters](http://mongoosejs.com/docs/2.7.x/docs/getters-setters.html)，虚函数（[virtuals](http://mongoosejs.com/docs/guide.html#virtuals)）和[单一的嵌入式文档](http://mongoosejs.com/docs/subdocs.html#single-embedded)。

让我们看看一个基本schema类型看一个例子：一个字节的整数。创建一个新的schema类型，你需要继承`mongoose.SchemaType`并且将相应的属性添加到`mongoose.Schema.Types`。你需要实现一个方法是`cast()`方法。

```javascript
 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');
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mongoose.shujuwajue.com/guide/schemas/custom.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
