Schema
Schema 是什么
在 Mongoose 中,所有數(shù)據(jù)都由一個(gè) Schema 開始創(chuàng)建。每一個(gè) schema 都映射到一個(gè) Mongodb 的集合(collection),并定義了該集合(collection)中的文檔(document)的形式。
定義一個(gè)Scheme
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserScehma = new Schema({
name: { type: String, required: true },
createTime: { type: Date, default: Date.now },
favoriteIds: [String]
sex: String,
avatar: String,
vip: Boolean,
})
new Schema({}) 中的name 稱之為Schema 的鍵
Schema 中的每一個(gè)鍵都定義了一個(gè)文檔(document)的一個(gè)屬性。
這里我們定義:
用戶名name , 它將映射為String 的Schema 類,設(shè)置required: true 規(guī)定創(chuàng)建文檔(document)時(shí)name 必須設(shè)置。
注冊(cè)時(shí)間 createTime 會(huì)被映射為 Date 的 Schema 類型,如沒設(shè)置默認(rèn)為Date.now 的值。
會(huì)員 vip 會(huì)被映射為 Boolean 的 Schema 類型。
收藏的id 列表被映射為 字符串 Array 的Schema 類型,['1', '2', '3']。
允許的Schema類型有:
- String
- Number
- Date
- Buffer
- Boolean
- Mixed
- ObjectId
- Array
實(shí)例方法
調(diào)用者:通過Schema 創(chuàng)建Model 構(gòu)造出的實(shí)例
我們可以為Model 創(chuàng)建實(shí)例方法供Model 實(shí)例調(diào)用。
const animalSchema = new Schema({ name: String, type: String })
// 實(shí)例方法
animalSchema.methods.findSimilarTypes = async function() {
// this 為調(diào)用此方法的Model 實(shí)例對(duì)象,此實(shí)例使用Model 方法前還需要指定model
return this.model('Animal').findOne({ type: this.type })
}
const Animal = mongoose.model('Animal', animalSchema)
const dog = new Animal({ type: 'dog' })
dog.findSimilarTypes().then(animal => console.log(animal.name)) // woff
靜態(tài)方法
調(diào)用者:通過Schema 創(chuàng)建的Model
我們可以為Model 創(chuàng)建靜態(tài)方法供Model 調(diào)用。
const animalSchema = new Schema({ name: String, type: String })
// 靜態(tài)方法
animalSchema.statics.findByName = async function(name) {
return this.findOne({ name })
}
const Animal = mongoose.model('Animal', animalSchema)
Animal.findByName('tom').then(animal => console.log(animal.name)) // tom
查詢助手
調(diào)用者:通過Schema 創(chuàng)建的Model
為Model 查詢后的結(jié)果(query)設(shè)置特定方法
// 查詢助手
animalSchema.query.byName = async function(name) {
return this.find({ name })
}
const Animal = mongoose.model('Animal', animalSchema)
Animal.find().byName('tom').then(animal => console.log(animal.name)) // tom
// 先查詢了所有動(dòng)物,再?gòu)慕Y(jié)果query里找到tom
索引
mongodb 每個(gè)document 都有一個(gè)_id 的主鍵也就是第一索引,同時(shí)也支持創(chuàng)建第二索引。
獨(dú)立索引:
1.在定義時(shí)Schema 內(nèi)創(chuàng)建也可用Schema.index創(chuàng)建。
2.根據(jù)單個(gè)field 查找時(shí)使用
組合索引:
1.由Schema.index創(chuàng)建。
2.當(dāng)需要既要查找field1 又要查找field2 時(shí)使用
設(shè)置:
設(shè)置索引1升序索引、-1降序索引
unique: true 設(shè)置為唯一索引
const animalSchema = new Schema({
name: { type: String, index: true }, // 獨(dú)立索引
type: String,
numbers: { type: [String], index: true } // 獨(dú)立索引
})
animalSchema.index({ name: 1, type: -1 }) // 組合索引
animalSchema.index({ type: -1 }, { unique: true }) // 降序、唯一索引
const Animal = mongoose.model('Animal', animalSchema)

圖中是我們創(chuàng)建的索引,可以看出name_1_type_-1 是一個(gè)組合索引,name_1 和type_-1 也是一個(gè)獨(dú)立索引。