Schema(模式)
Schema()
Schema.Types
Schema.indexTypes
Schema.prototype.add()
Schema.prototype.alias()
Schema.prototype.childSchemas
Schema.prototype.clearIndexes()
Schema.prototype.clone()
Schema.prototype.discriminator()
Schema.prototype.eachPath()
Schema.prototype.get()
Schema.prototype.index()
Schema.prototype.indexes()
Schema.prototype.loadClass()
Schema.prototype.method()
Schema.prototype.obj
Schema.prototype.omit()
Schema.prototype.path()
Schema.prototype.pathType()
Schema.prototype.paths
Schema.prototype.pick()
Schema.prototype.plugin()
Schema.prototype.post()
Schema.prototype.pre()
Schema.prototype.queue()
Schema.prototype.remove()
Schema.prototype.removeIndex()
Schema.prototype.removeVirtual()
Schema.prototype.requiredPaths()
Schema.prototype.searchIndex()
Schema.prototype.set()
Schema.prototype.static()
Schema.prototype.virtual()
Schema.prototype.virtualpath()
Schema.prototype.virtuals
Schema.reserved
Schema()
參數
[definition]
«Object|Schema|Array» 可以是以下其中之一:描述模式路徑的物件、要複製的模式,或物件和模式的陣列[options]
«Object»
繼承自
Schema 建構函式。
範例
const child = new Schema({ name: String });
const schema = new Schema({ name: String, age: Number, children: [child] });
const Tree = mongoose.model('Tree', schema);
// setting schema options
new Schema({ name: String }, { id: false, autoIndex: false })
選項
- autoIndex: bool - 預設為 null (表示使用連線的 autoIndex 選項)
- autoCreate: bool - 預設為 null (表示使用連線的 autoCreate 選項)
- bufferCommands: bool - 預設為 true
- bufferTimeoutMS: number - 預設為 10000 (10 秒)。如果啟用
bufferCommands
,則 Mongoose 會等待重新建立連線的時間,然後才會發生錯誤。 - capped: bool | number | object - 預設為 false
- collection: string - 沒有預設值
- discriminatorKey: string - 預設為
__t
- id: bool - 預設為 true
- _id: bool - 預設為 true
- minimize: bool - 控制手動呼叫時的 document#toObject 行為 - 預設為 true
- read: string
- readConcern: object - 預設為 null,用於為所有查詢設定預設的讀取關注。
- writeConcern: object - 預設為 null,用於覆寫MongoDB 伺服器的預設寫入關注設定
- shardKey: object - 預設為
null
- strict: bool - 預設為 true
- strictQuery: bool - 預設為 false
- toJSON - object - 沒有預設值
- toObject - object - 沒有預設值
- typeKey - string - 預設為 'type'
- validateBeforeSave - bool - 預設為
true
- validateModifiedOnly - bool - 預設為
false
- versionKey: string 或 object - 預設為 "__v"
- optimisticConcurrency: bool - 預設為 false。設定為 true 以啟用樂觀並行。
- collation: object - 預設為 null (表示不使用定序)
- timeseries: object - 預設為 null (表示此模式的集合不會是時間序列集合)
- selectPopulatedPaths: boolean - 預設為
true
- skipVersioning: object - 要從版本控制中排除的路徑
- timestamps: object 或 boolean - 預設為
false
。如果為 true,Mongoose 會將createdAt
和updatedAt
屬性新增至您的模式,並為您管理這些屬性。 - pluginTags: 字串陣列 - 預設為
undefined
。如果設定且插件呼叫時帶有tags
選項,則只會將該插件套用至具有相符標籤的模式。 - virtuals: object - 要定義的虛擬屬性,是
.virtual
的別名 - [collectionOptions]: 具有傳遞至
createCollection()
的選項的物件,當呼叫Model.createCollection()
或將autoCreate
設定為 true 時。
巢狀模式的選項
excludeIndexes
: bool - 預設為false
。如果為true
,則跳過在此模式的路徑上建立索引。
注意
當巢狀模式時,(在上面的範例中為 children
),請務必先宣告子模式,然後再將其傳遞至父模式。
Schema.Types
類型
- «屬性»
各種內建的 Mongoose 模式類型。
範例
const mongoose = require('mongoose');
const ObjectId = mongoose.Schema.Types.ObjectId;
類型
使用此公開的 Mixed
SchemaType 存取,我們可以在我們的模式中使用它們。
const Mixed = mongoose.Schema.Types.Mixed;
new mongoose.Schema({ _user: Mixed })
Schema.indexTypes
類型
- «屬性»
允許的索引類型
Schema.prototype.add()
參數
obj
«Object|Schema» 具有要新增的路徑的純物件,或其他模式[prefix]
«String» 要將新加入的路徑作為前綴的路徑
返回
- «Schema» Schema 實例
將 key 路徑/模式類型對新增至此模式。
範例
const ToySchema = new Schema();
ToySchema.add({ name: 'string', color: 'string', price: 'number' });
const TurboManSchema = new Schema();
// You can also `add()` another schema and copy over all paths, virtuals,
// getters, setters, indexes, methods, and statics.
TurboManSchema.add(ToySchema).add({ year: Number });
Schema.prototype.alias()
參數
path
«String» 要設為別名的真實路徑alias
«String|Array[String]» 要用作path
別名的路徑
返回
- «Schema» Schema 實例
為 path
新增別名。這表示取得或設定 alias
等同於取得或設定 path
。
範例
const toySchema = new Schema({ n: String });
// Make 'name' an alias for 'n'
toySchema.alias('n', 'name');
const Toy = mongoose.model('Toy', toySchema);
const turboMan = new Toy({ n: 'Turbo Man' });
turboMan.name; // 'Turbo Man'
turboMan.n; // 'Turbo Man'
turboMan.name = 'Turbo Man Action Figure';
turboMan.n; // 'Turbo Man Action Figure'
await turboMan.save(); // Saves { _id: ..., n: 'Turbo Man Action Figure' }
Schema.prototype.childSchemas
類型
- «屬性»
子模式的陣列(來自文件陣列和單一巢狀子文件)及其對應的編譯模型。陣列的每個元素都是一個具有 2 個屬性的物件:schema
和 model
。
這個屬性通常只對插件作者和進階使用者有用。您完全不需要與此屬性互動即可使用 mongoose。
Schema.prototype.clearIndexes()
返回
- «Schema» Schema 實例
從此模式中移除所有索引。
clearIndexes 只會從您的模式物件中移除索引。不會影響 MongoDB 中的索引。
範例
const ToySchema = new Schema({ name: String, color: String, price: Number });
ToySchema.index({ name: 1 });
ToySchema.index({ color: 1 });
// Remove all indexes on this schema
ToySchema.clearIndexes();
ToySchema.indexes(); // []
Schema.prototype.clone()
返回
- «Schema» 克隆的模式
返回模式的深層複製
範例
const schema = new Schema({ name: String });
const clone = schema.clone();
clone === schema; // false
clone.path('name'); // SchemaString { ... }
Schema.prototype.discriminator()
參數
name
«String» 判別器的名稱schema
«Schema» 判別的模式[options]
«Object» 判別器選項[options.value]
«String» 儲存在discriminatorKey
屬性中的字串。如果未指定,Mongoose 會使用name
參數。[options.clone=true]
«Boolean» 預設情況下,discriminator()
會克隆給定的schema
。設定為false
以跳過克隆。[options.overwriteModels=false]
«Boolean» 預設情況下,Mongoose 不允許您使用與另一個判別器相同的名稱來定義判別器。設定此選項可允許覆寫具有相同名稱的判別器。[options.mergeHooks=true]
«Boolean» 預設情況下,Mongoose 會將基本模式的鉤子與判別器模式的鉤子合併。將此選項設定為false
,以使 Mongoose 改用判別器模式的鉤子。[options.mergePlugins=true]
«Boolean» 預設情況下,Mongoose 會將基本模式的插件與判別器模式的插件合併。將此選項設定為false
,以使 Mongoose 改用判別器模式的插件。
返回
- «Schema» Schema 實例
透過在現有模式上套用判別器來繼承模式。
範例
const eventSchema = new mongoose.Schema({ timestamp: Date }, { discriminatorKey: 'kind' });
const clickedEventSchema = new mongoose.Schema({ element: String }, { discriminatorKey: 'kind' });
const ClickedModel = eventSchema.discriminator('clicked', clickedEventSchema);
const Event = mongoose.model('Event', eventSchema);
Event.discriminators['clicked']; // Model { clicked }
const doc = await Event.create({ kind: 'clicked', element: '#hero' });
doc.element; // '#hero'
doc instanceof ClickedModel; // true
Schema.prototype.eachPath()
參數
fn
«Function» 回呼函數
返回
- «Schema» this
迭代模式的路徑,類似於 Array#forEach。
回呼會傳遞路徑名稱和 schemaType 實例。
範例
const userSchema = new Schema({ name: String, registeredAt: Date });
userSchema.eachPath((pathname, schematype) => {
// Prints twice:
// name SchemaString { ... }
// registeredAt SchemaDate { ... }
console.log(pathname, schematype);
});
Schema.prototype.get()
參數
key
«String» 要取得目前值的選項名稱
返回
- «Any» 選項的值
取得模式選項。
範例
schema.get('strict'); // true
schema.set('strict', false);
schema.get('strict'); // false
Schema.prototype.index()
參數
fields
«Object» 要建立索引的欄位,其中包含順序,可用值:1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text'
[options]
«Object» 要傳遞給 MongoDB 驅動程式的createIndex()
函數的選項[options.expires=null]
«String|number» Mongoose 特有的語法糖,使用 ms 將expires
選項轉換為秒,用於上面連結中的expireAfterSeconds
。[options.language_override=null]
«String» 告訴 mongodb 使用指定的欄位而不是language
來解析文字索引。
Schema.prototype.indexes()
返回
- «Array» 模式中定義的索引清單
返回此 schema 宣告的索引列表,透過 schema.index()
或在路徑選項中使用 index: true
。索引表示為一個陣列 [spec, options]
。
範例
const userSchema = new Schema({
email: { type: String, required: true, unique: true },
registeredAt: { type: Date, index: true }
});
// [ [ { email: 1 }, { unique: true, background: true } ],
// [ { registeredAt: 1 }, { background: true } ] ]
userSchema.indexes();
外掛可以使用此函數的回傳值來修改 schema 的索引。例如,以下外掛預設使每個索引都是唯一的。
function myPlugin(schema) {
for (const index of schema.indexes()) {
if (index[1].unique === undefined) {
index[1].unique = true;
}
}
}
Schema.prototype.loadClass()
參數
model
«Function» 要載入的類別[virtualsOnly]
«Boolean» 如果為真值,則僅從類別提取虛擬屬性,而不是方法或靜態屬性
將 ES6 類別載入到 schema 中。將 setters + getters、靜態方法和 實例方法對應到 schema 的虛擬屬性、靜態屬性和 方法。
範例
const md5 = require('md5');
const userSchema = new Schema({ email: String });
class UserClass {
// `gravatarImage` becomes a virtual
get gravatarImage() {
const hash = md5(this.email.toLowerCase());
return `https://www.gravatar.com/avatar/${hash}`;
}
// `getProfileUrl()` becomes a document method
getProfileUrl() {
return `https://mysite.com/${this.email}`;
}
// `findByEmail()` becomes a static
static findByEmail(email) {
return this.findOne({ email });
}
}
// `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
// and a `findByEmail()` static
userSchema.loadClass(UserClass);
Schema.prototype.method()
參數
name
«String|Object» 單一函數的方法名稱,或 "字串-函數" 配對的物件。[fn]
«Function» 單一函數定義中的函數。
將實例方法新增到由此 schema 編譯的模型建構的文件中。
範例
const schema = kittySchema = new Schema(..);
schema.method('meow', function () {
console.log('meeeeeoooooooooooow');
})
const Kitty = mongoose.model('Kitty', schema);
const fizz = new Kitty;
fizz.meow(); // meeeeeooooooooooooow
如果傳遞一個名稱/函數配對的雜湊表作為唯一參數,則每個名稱/函數配對都將被新增為方法。
schema.method({
purr: function () {}
, scratch: function () {}
});
// later
const fizz = new Kitty;
fizz.purr();
fizz.scratch();
注意:Schema.method()
將實例方法新增到 Schema.methods
物件。您也可以直接將實例方法新增到 Schema.methods
物件,如指南中所見。
Schema.prototype.obj
類型
- «屬性»
傳遞給 schema 建構函式的原始物件
範例
const schema = new Schema({ a: String }).add({ b: String });
schema.obj; // { a: String }
Schema.prototype.omit()
參數
paths
«Array[String]» 要從新 Schema 中省略的路徑列表[options]
«Object» 傳遞給新 Schema 建構函式的選項(與new Schema(.., Options)
相同)。如果未設定,則預設為this.options
。
返回
- «Schema»
返回一個新的 schema,其中包含原始 schema 的 paths
,減去省略的路徑。
此方法類似於 Mongoose schema 的 Lodash 的 omit()
函數。
範例
const schema = Schema({ name: String, age: Number });
// Creates a new schema omitting the `age` path
const newSchema = schema.omit(['age']);
newSchema.path('name'); // SchemaString { ... }
newSchema.path('age'); // undefined
Schema.prototype.path()
參數
path
«String» 要取得/設定的路徑名稱[obj]
«Object» 要將路徑設定為的類型,如果提供,則將設定路徑,否則將取得路徑
取得/設定 schema 路徑。
設定路徑 (如果 arity 為 2) 取得路徑 (如果 arity 為 1)
範例
schema.path('name') // returns a SchemaType
schema.path('name', Number) // changes the schemaType of `name` to Number
Schema.prototype.pathType()
參數
path
«String»
返回
- «String»
返回此 schema 的 path
的 pathType。
給定一個路徑,返回它是真實、虛擬、巢狀或臨時/未定義的路徑。
範例
const s = new Schema({ name: String, nested: { foo: String } });
s.virtual('foo').get(() => 42);
s.pathType('name'); // "real"
s.pathType('nested'); // "nested"
s.pathType('foo'); // "virtual"
s.pathType('fail'); // "adhocOrUndefined"
Schema.prototype.paths
類型
- «屬性»
在此 schema 上定義的路徑。鍵是此 schema 中的頂級路徑,值是 SchemaType 類的實例。
範例
const schema = new Schema({ name: String }, { _id: false });
schema.paths; // { name: SchemaString { ... } }
schema.add({ age: Number });
schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } }
Schema.prototype.pick()
參數
paths
«Array[String]» 要為新 Schema 選取的路徑列表[options]
«Object» 傳遞給新 Schema 建構函式的選項(與new Schema(.., Options)
相同)。如果未設定,則預設為this.options
。
返回
- «Schema»
返回一個新的 schema,其中包含從此 schema 選取的 paths
。
此方法類似於 Mongoose schema 的 Lodash 的 pick()
函數。
範例
const schema = Schema({ name: String, age: Number });
// Creates a new schema with the same `name` path as `schema`,
// but no `age` path.
const newSchema = schema.pick(['name']);
newSchema.path('name'); // SchemaString { ... }
newSchema.path('age'); // undefined
Schema.prototype.plugin()
參數
plugin
«Function» 外掛的回呼[opts]
«Object» 傳遞給外掛的選項[opts.deduplicate=false]
«Boolean» 如果為 true,則忽略重複的外掛(使用===
的相同fn
參數)
參見
為此 schema 註冊外掛。
範例
const s = new Schema({ name: String });
s.plugin(schema => console.log(schema.path('name').path));
mongoose.model('Test', s); // Prints 'name'
或使用選項
const s = new Schema({ name: String });
s.plugin((schema, opts) => console.log(opts.text, schema.path('name').path), { text: "Schema Path Name:" });
mongoose.model('Test', s); // Prints 'Schema Path Name: name'
Schema.prototype.post()
參數
methodName
«String|RegExp|Array[String]» 方法名稱或符合方法名稱的正規表示式[options]
«Object»[options.document]
«Boolean» 如果name
是文件和查詢中介軟體的 hook,則設定為true
以在文件 middleware 上執行。[options.query]
«Boolean» 如果name
是文件和查詢中介軟體的 hook,則設定為true
以在查詢 middleware 上執行。fn
«Function» 回呼
參見
定義文件的 post hook
const schema = new Schema(..);
schema.post('save', function (doc) {
console.log('this fired after a document was saved');
});
schema.post('find', function(docs) {
console.log('this fired after you ran a find query');
});
schema.post(/Many$/, function(res) {
console.log('this fired after you ran `updateMany()` or `deleteMany()`');
});
const Model = mongoose.model('Model', schema);
const m = new Model(..);
m.save(function(err) {
console.log('this fires after the `post` hook');
});
m.find(function(err, docs) {
console.log('this fires after the post find hook');
});
Schema.prototype.pre()
參數
methodName
«String|RegExp|Array[String]» 方法名稱或符合方法名稱的正規表示式[options]
«Object»[options.document]
«Boolean» 如果name
是文件和查詢中介軟體的 hook,則設定為true
以在文件 middleware 上執行。例如,設定options.document
為true
以將此 hook 應用於Document#deleteOne()
而不是Query#deleteOne()
。[options.query]
«Boolean» 如果name
是文件和查詢中介軟體的 hook,則設定為true
以在查詢 middleware 上執行。callback
«Function»
定義模型的 pre hook。
範例
const toySchema = new Schema({ name: String, created: Date });
toySchema.pre('save', function(next) {
if (!this.created) this.created = new Date;
next();
});
toySchema.pre('validate', function(next) {
if (this.name !== 'Woody') this.name = 'Woody';
next();
});
// Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
toySchema.pre(/^find/, function(next) {
console.log(this.getFilter());
});
// Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
console.log(this.getFilter());
});
toySchema.pre('deleteOne', function() {
// Runs when you call `Toy.deleteOne()`
});
toySchema.pre('deleteOne', { document: true }, function() {
// Runs when you call `doc.deleteOne()`
});
Schema.prototype.queue()
參數
name
«String» 要稍後呼叫的文件方法名稱args
«Array» 傳遞給方法的參數
將方法呼叫新增到佇列。
範例
schema.methods.print = function() { console.log(this); };
schema.queue('print', []); // Print the doc every one is instantiated
const Model = mongoose.model('Test', schema);
new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }'
Schema.prototype.remove()
參數
path
«String|Array» 要移除的路徑
返回
- «Schema» Schema 實例
移除給定的 path
(或 [paths
])。
範例
const schema = new Schema({ name: String, age: Number });
schema.remove('name');
schema.path('name'); // Undefined
schema.path('age'); // SchemaNumber { ... }
或作為陣列
schema.remove(['name', 'age']);
schema.path('name'); // Undefined
schema.path('age'); // Undefined
Schema.prototype.removeIndex()
參數
index
«Object|string» 名稱或索引規格
返回
- «Schema» Schema 實例
依名稱或索引規格移除索引。
removeIndex 僅從您的 schema 物件中移除索引。不會影響 MongoDB 中的索引。
範例
const ToySchema = new Schema({ name: String, color: String, price: Number });
// Add a new index on { name, color }
ToySchema.index({ name: 1, color: 1 });
// Remove index on { name, color }
// Keep in mind that order matters! `removeIndex({ color: 1, name: 1 })` won't remove the index
ToySchema.removeIndex({ name: 1, color: 1 });
// Add an index with a custom name
ToySchema.index({ color: 1 }, { name: 'my custom index name' });
// Remove index by name
ToySchema.removeIndex('my custom index name');
Schema.prototype.removeVirtual()
參數
path
«String|Array» 要移除的虛擬路徑。
從 schema 中移除給定的虛擬屬性或多個虛擬屬性。
Schema.prototype.requiredPaths()
參數
invalidate
«Boolean» 重新整理快取
返回
- «Array»
返回此 schema 需要的路徑字串陣列。
範例
const s = new Schema({
name: { type: String, required: true },
age: { type: String, required: true },
notes: String
});
s.requiredPaths(); // [ 'age', 'name' ]
Schema.prototype.searchIndex()
參數
description
«Object» 索引選項,包括name
和definition
description.name
«String»description.definition
«Object»
返回
- «Schema» Schema 實例
新增一個 Atlas 搜尋索引,Mongoose 將使用 Model.createSearchIndex()
建立該索引。此函數僅在連線到 MongoDB Atlas 時有效。
範例
const ToySchema = new Schema({ name: String, color: String, price: Number });
ToySchema.searchIndex({ name: 'test', definition: { mappings: { dynamic: true } } });
Schema.prototype.set()
參數
key
«String» 要設定值的選項名稱[value]
«Object» 要將選項設定為的值,如果未傳遞,則選項將重設為預設值[tags]
«Array<string>» 如果 key === 'read',則要新增到讀取偏好的標籤
參見
設定 schema 選項。
範例
schema.set('strict'); // 'true' by default
schema.set('strict', false); // Sets 'strict' to false
schema.set('strict'); // 'false'
Schema.prototype.static()
參數
name
«String|Object» 單一函數的方法名稱,或 "字串-函數" 配對的物件。[fn]
«Function» 單一函數定義中的函數。
參見
將靜態「類別」方法新增到由此 schema 編譯的模型中。
範例
const schema = new Schema(..);
// Equivalent to `schema.statics.findByName = function(name) {}`;
schema.static('findByName', function(name) {
return this.find({ name: name });
});
const Drink = mongoose.model('Drink', schema);
await Drink.findByName('LaCroix');
如果傳遞一個名稱/函數配對的雜湊表作為唯一參數,則每個名稱/函數配對都將被新增為方法。
schema.static({
findByName: function () {..}
, findByCost: function () {..}
});
const Drink = mongoose.model('Drink', schema);
await Drink.findByName('LaCroix');
await Drink.findByCost(3);
如果傳遞一個名稱/函數配對的雜湊表作為唯一參數,則每個名稱/函數配對都將被新增為靜態屬性。
Schema.prototype.virtual()
參數
name
«String» 虛擬屬性的名稱[options]
«Object»[options.ref]
«String|Model» 模型名稱或模型實例。將此標記為填充虛擬屬性。[options.localField]
«String|Function» 填充虛擬屬性所必需。有關更多資訊,請參閱填充虛擬屬性文件。[options.foreignField]
«String|Function» 填充虛擬屬性所必需。有關更多資訊,請參閱填充虛擬屬性文件。[options.justOne=false]
«Boolean|Function» 僅適用於填充虛擬屬性。如果為真值,則將是單個文件或null
。否則,填充虛擬屬性將是一個陣列。[options.count=false]
«Boolean» 僅適用於填充虛擬屬性。如果為真值,則當您populate()
時,此填充虛擬屬性將包含文件數量而不是文件本身。[options.get=null]
«Function|null» 為此虛擬屬性新增一個getter,以轉換填充的文件。[options.match=null]
«Object|Function» 應用預設的match
選項來填充,為填充查詢新增一個額外的篩選器。
返回
- «VirtualType»
使用給定的名稱建立虛擬類型。
Schema.prototype.virtualpath()
參數
name
«String» 要取得的虛擬屬性名稱
返回
- «VirtualType,null»
返回具有給定 name
的虛擬類型。
Schema.prototype.virtuals
類型
- «屬性»
包含在此 schema 上定義的所有虛擬屬性的物件。物件的鍵是虛擬路徑,值是 VirtualType
的實例。
這個屬性通常只對插件作者和進階使用者有用。您完全不需要與此屬性互動即可使用 mongoose。
範例
const schema = new Schema({});
schema.virtual('answer').get(() => 42);
console.log(schema.virtuals); // { answer: VirtualType { path: 'answer', ... } }
console.log(schema.virtuals['answer'].getters[0].call()); // 42
Schema.reserved
類型
- «屬性»
保留的文件鍵。
此物件中的鍵是在 schema 宣告中警告的名稱,因為它們可能會破壞 Mongoose/Mongoose 外掛的功能。如果您使用 new Schema()
建立具有其中一個屬性名稱的 schema,則 Mongoose 將記錄警告。
- _posts
- _pres
- collection
- emit
- errors
- get
- init
- isModified
- isNew
- listeners
- modelName
- on
- once
- populated
- prototype
- remove
- removeListener
- save
- schema
- toObject
- validate
注意:允許使用這些術語作為方法名稱,但請自行承擔風險,因為它們可能是您要覆蓋的現有 mongoose 文件方法。
const schema = new Schema(..);
schema.methods.init = function () {} // potentially breaking