Mongoose Schema类型

SchemaTypes 可以设置Strings和Numbers,默认defaults,验证validation,getters setters,等等一般特性.

defaultsvalidationgetterssettersfield selection defaults for queries and .点击查看具体API

SchemaTypes支持的类型

例子Example

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],
  ofArrays:   [[]],
  ofArrayOfNumbers: [[Number]],
  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);

SchemaType Options

你可以直接声明一个schema type 类型或者使用一个对象加一个type属性

var schema1 = new Schema({
  test: String // `test` is a path of type String
});

var schema2 = new Schema({
  test: { type: String } // `test` is a path of type string
});

除了type属性,还可以增加额外的属性,例如想设置string为小写。增加lowercase.

var schema2 = new Schema({
  test: {
    type: String,
    lowercase: true // Always convert `test` to lowercase
  }
});

lowercase只支持字符串strings.有些options支持所有schema,有些只支持某些schema types。

所有 Schema Types
  • required: 是否必须提供,boolean or function,required validator
  • default: Any or function, 默认值可以是funciton.
  • select: boolean, specifies default projections for queries
  • validate: function, adds a validator function for this property 验证
  • get: function, defines a custom getter for this property using Object.defineProperty().
  • set: function, defines a custom setter for this property using Object.defineProperty().
  • alias: string, mongoose >= 4.10.0 only. Defines a virtual with the given name that gets/sets this path.
var numberSchema = new Schema({
  integerOnly: {
    type: Number,
    get: v => Math.round(v),
    set: v => Math.round(v),
    alias: 'i'
  }
});

var Number = mongoose.model('Number', numberSchema);

var doc = new Number();
doc.integerOnly = 2.001;
doc.integerOnly; // 2
doc.i; // 2
doc.i = 3.001;
doc.integerOnly; // 3
doc.i; // 3
Indexes 索引

You can also define MongoDB indexes using schema type options.

Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.

使用索引可以非常高效的执行查询,如果不用index,mongodb会执行全面扫描。

  • index: boolean, whether to define an index on this property.
  • unique: boolean, whether to define a unique index on this property.唯一索引
  • sparse: boolean, whether to define a sparse index on this property.稀疏索引

By default, MongoDB creates a unique index on the _id field during the creation of a collection.

详细查看https://docs.mongodb.com/manual/indexes/

MongoDB默认创建一个_id字段是唯一索引。

var schema2 = new Schema({
  test: {
    type: String,
    index: true,
    unique: true // Unique index. If you specify `unique: true`
    // specifying `index: true` is optional if you do `unique: true`
  }
});
String
  • lowercase: boolean, whether to always call .toLowerCase() on the value
  • uppercase: boolean, whether to always call .toUpperCase() on the value
  • 大小写
  • trim: boolean, whether to always call .trim() on the value
  • 除空格
  • match: RegExp, creates a validator that checks if the value matches the given regular expression
  • 正则
  • enum: Array, creates a validator that checks if the value is in the given array.
  • 枚举
Number
  • min: Number, creates a validator that checks if the value is greater than or equal to the given minimum.
  • 最小
  • max: Number, creates a validator that checks if the value is less than or equal to the given maximum.
  • 最大
Date
  • min: Date
  • max: Date

Usage notes:使用提示

Dates

Built-in Date methods are not hooked into the mongoose change tracking logic which in English means that if you use a Date in your document and modify it with a method like setMonth(), mongoose will be unaware of this change and doc.save() will not persist this modification. If you must modify Date types using built-in methods, tell mongoose about the change with doc.markModified('pathToYourDate') before saving.

使用内置Date方法不会被mongoose察觉修改数据。除非使用save()前用doc.markModified('pathToYourDate')

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

An “anything goes” SchemaType, its flexibility comes at a trade-off of it being harder to maintain. Mixed is available either through Schema.Types.Mixed or by passing an empty object literal. The following are equivalent:

可以放任意类型的类型。

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

Since it is a schema-less type, you can change the value to anything else you like, but Mongoose loses the ability to auto detect and save those changes. To “tell” Mongoose that the value of a Mixed type has changed, call the.markModified(path) method of the document passing the path to the Mixed type you just changed.

mongoose没有能力自动识别和保存Mixed 所以保存前需要使用.markModified(path)

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

ObjectIds 就是obejctId,没啥特别的。

To specify a type of ObjectId, useSchema.Types.ObjectId in your declaration.

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 数组

Provide creation of arrays ofSchemaTypes orSub-Documents.

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

Note: specifying an empty array is equivalent toMixed. The following all create arrays ofMixed:

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

Arrays implicitly have a default value of `[]` (empty array).

var Toy = mongoose.model('Test', ToySchema);
console.log((new Toy()).toys); // []

To overwrite this default, you need to set the default value to `undefined`

var ToySchema = new Schema({
  toys: {
    type: [ToySchema],
    default: undefined
  }
});

If an array is marked as `required`, it must have at least one element.

var ToySchema = new Schema({
  toys: {
    type: [ToySchema],
    required: true
  }
});
var Toy = mongoose.model('Toy', ToySchema);
Toy.create({ toys: [] }, function(error) {
  console.log(error.errors['toys'].message); // Path "toys" is required.
});

可以自定义类型

Search the plugins site for compatible types like mongoose-longmongoose-int32 and other|types. To create your own custom schema take a look atCreating a Basic Custom Schema Type.

The `schema.path()` Function

获取实例化schema type

The schema.path() function returns the instantiated schema type for a given path.

var sampleSchema = new Schema({ name: { type: String, required: true } });
console.log(sampleSchema.path('name'));
// Output looks like:
/**
 * SchemaString {
 *   enumValues: [],
 *   regExp: null,
 *   path: 'name',
 *   instance: 'String',
 *   validators: ...
 */

You can use this function to inspect the schema type for a given path, including what validators it has and what the type is.

发表评论

邮箱地址不会被公开。