Mongoose之 SchemaTypes 數據類型


SchemaTypes 數據類型

SchemaTypes handle definition of path defaults, validation, getters, setters, field selection defaults for queries and other general characteristics for Strings and Numbers. Check out their respective API documentation for more detail.

數據類型用於定義默認路徑, 驗證方式, 獲取/設置方法,用於數據庫查詢的默認字段,以及其他針對字符串與數字的特性。關於詳細信息請查閱相關API文檔。

譯注:默認路徑即某個域相對於文檔而言的路徑,如{a: 1}這個文檔中,若指定路徑為’a’,即可訪問到1這個數據。

Following are all valid Schema Types.
接下來是Mongoose中所有可用的數據類型。

  • String
    字符串
  • Number
    數字
  • Date
    日期
  • Buffer
    緩沖區
  • Boolean
    布爾值
  • Mixed
    混合
  • Objectid
    對象ID
  • Array
    數組

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],
  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);

 

 

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.

Mongoose不跟蹤JS內建的日期方法對數據造成的改變。這意味着如果你在文檔中使用Date 類型並用setMonth之類的方法去修改它,Mongoose不會意識到它的改變,調用doc.save方法保存時不會保留這個修改。如果你一定要用JS內建的方法修改Date類型的數據,在保存之前用doc.markModified 方法告訴Mongoose這個改變。

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:

混合型是一種“存啥都行”的數據類型,它的靈活性來自於對可維護性的妥協。Mixed類型用Schema.Types.Mixed 或者一個字面上的空對象{}來定義。下面的定義是等價的:

var Any = new Schema({ any: {} });
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 沒有能力去自動檢測和保存這些改動。請通過調用doc.markModified 方法來告訴Mongoose某個混合類型的值被改變了。

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

 

ObjectIds 對象ID型

To specify a type of ObjectId, use Schema.Types.ObjectId in your declaration.
Schema.Types.ObjectId 來聲明一個對象ID類型。

譯注:對象ID同MongoDB內置的_id 的類型。由24位Hash字符串。

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 of SchemaTypes or Sub-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 to Mixed. The following all create arrays of Mixed:
注意:用一個空數組來定義等價於創建一個混合型的數組。下面都是創建混合型數組的例子:

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

 

Creating Custom Types 創建自定義類型

Mongoose can also be extended with custom SchemaTypes. Search the plugins site for compatible types like mongoose-long, mongoose-int32 and other types. To create your own custom schema take a look at Creating a Basic Custom Schema Type.
Mongoose也支持使用自定義的數據類型來拓展功能。從Mongoose插件站搜索合適的類型,比如mongoose-long,mongoose-int32或者其他類型。 想要自己創建類型的話請參考創建一個基礎的自定義數據類型。



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM