# 模式类型（types）

> 原文：[SchemaTypes](http://mongoosejs.com/docs/schematypes.html)\
> 翻译：小虾米（QQ:509129）

## SchemaTypes

SchemaTypes 为[查询](http://mongoosejs.com/docs/api.html#query-js)处理定义path [defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default), [validation](http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate), [getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get), [setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set), [field selection defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-select) ，以及为了[字符串](http://mongoosejs.com/docs/api.html#schema-string-js)和[数值](http://mongoosejs.com/docs/api.html#schema-number-js)的其他一般特征。检查他们各自的的更多细节的 API 文档。

以下是所有有效的[Schema Types](http://mongoosejs.com/docs/api.html#schema_Schema.Types)。

* [String](http://mongoosejs.com/docs/api.html#schema-string-js)
* [Number](http://mongoosejs.com/docs/api.html#schema-number-js)
* [Date](http://mongoosejs.com/docs/api.html#schema-date-js)
* [Buffer](http://mongoosejs.com/docs/api.html#schema-buffer-js)
* Boolean
* Mixed
* [Objectid](http://mongoosejs.com/docs/api.html#schema-objectid-js)
* Array

#### 例子

```javascript
var schema = new Schema({
  name:    String,
  binary:  Buffer,
  living:  Boolean,
  updated: { type: Date, default: Date.now },
  age:     { type: Number, min: 18, max: 65 },
  mixed:   Schema.Types.Mixed,
  _someId: Schema.Types.ObjectId,
  array:      [],
  ofString:   [String],
  ofNumber:   [Number],
  ofDates:    [Date],
  ofBuffer:   [Buffer],
  ofBoolean:  [Boolean],
  ofMixed:    [Schema.Types.Mixed],
  ofObjectId: [Schema.Types.ObjectId],
  nested: {
    stuff: { type: String, lowercase: true, trim: true }
  }
})

// example use

var Thing = mongoose.model('Thing', schema);

var m = new Thing;
m.name = 'Statue of Liberty';
m.age = 125;
m.updated = new Date;
m.binary = new Buffer(0);
m.living = false;
m.mixed = { any: { thing: 'i want' } };
m.markModified('mixed');
m._someId = new mongoose.Types.ObjectId;
m.array.push(1);
m.ofString.push("strings!");
m.ofNumber.unshift(1,2,3,4);
m.ofDates.addToSet(new Date);
m.ofBuffer.pop();
m.ofMixed = [1, [], 'three', { four: 5 }];
m.nested.stuff = 'good';
m.save(callback);
```

### 使用说明：

#### Dates

[内置的日期的方法](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)在mongoose用英语改变跟踪逻辑不是钩子，意味着如果您在文档中使用日期，并用类似的方法进行修改如`setmonth()`，mongoose不知道这种变化，并且`doc.save()`不会坚持这样的修改。如果你必须使用内置的方法修改日期类型，保存之前告诉mongoose关于`doc.markModified('pathToYourDate')`的变化。

```javascript
var Assignment = mongoose.model('Assignment', { dueDate: Date });
Assignment.findOne(function (err, doc) {
  doc.dueDate.setMonth(3);
  doc.save(callback); // THIS DOES NOT SAVE YOUR CHANGE

  doc.markModified('dueDate');
  doc.save(callback); // works
})
```

#### Mixed

一个“什么都行”的SchemaType，它的灵活性会带来权衡它难维护。混合类型可通过`schema.types.mixed`或通过传递一个空的对象。以下是等价的：

```javascript
var Any = new Schema({ any: {} });
var Any = new Schema({ any: Schema.Types.Mixed });
```

因为它是一个无模式的类型，您可以将值更改为其他任何你喜欢的东西，但是Mongoose失去自动检测和保存这些变化的能力。“告诉”Mongoose，混合型的价值观已经改变了，调用.markModified(path)方法使文档传递路径到您刚刚更改的混合类型。

```javascript
person.anything = { x: [3, 4, { y: "changed" }] };
person.markModified('anything');
person.save(); // anything will now get saved
```

#### ObjectIds

指定一个ObjectId类型，使用`Schema.Types`。ObjectId在你的声明中。

```javascript
var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var Car = new Schema({ driver: ObjectId });
// or just Schema.ObjectId for backwards compatibility with v2
```

#### Arrays

提供创建数组的[`SchemaTypes`](http://mongoosejs.com/docs/subdocs.html)或[子文档](http://mongoosejs.com/docs/subdocs.html)。

```javascript
var ToySchema = new Schema({ name: String });
var ToyBox = new Schema({
  toys: [ToySchema],
  buffers: [Buffer],
  string:  [String],
  numbers: [Number]
  // ... etc
});
```

注：指定一个空数组是相当于混合类型（`Mixed`）。以下所有创建混合数组：

```javascript
var Empty1 = new Schema({ any: [] });
var Empty2 = new Schema({ any: Array });
var Empty3 = new Schema({ any: [Schema.Types.Mixed] });
var Empty4 = new Schema({ any: [{}] });
```

### 创建自定义类型

Mongoose也可以扩展自定义 SchemaTypes 。搜索兼容类型的[插件](http://plugins.mongoosejs.com/)站点，如，[ mongoose-long](https://github.com/aheckmann/mongoose-long)，[mongoose-int32](https://github.com/vkarpov15/mongoose-int32)以及[其他类型](https://github.com/OpenifyIt/mongoose-types)。要创建您自己的自定义schema，请看一看[创建基本的自定义schema类型](http://mongoosejs.com/docs/customschematypes.html)。

### 下一步

既然我们已经掌握了SchemaTypes，让我们看一看[模型](http://mongoosejs.com/docs/models.html)。
