Mongoose - 在 NodeJs 中優雅地建立 MongoDb 對象模型
Schema
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
在 Mongoose 中,所有東西都從一個 Schema 開始。每一個 schema 都映射到一個 MongoDb 的集合,并定義了該集合中的文檔的形式。
定義一個 Schema:
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: String,
pass: String,
email: String,
createTime: Date,
lastLogin: Date
});
Schema 中的每一個鍵都定義了一個文檔的一個屬性。在上面的例子中,我們定義了用戶名 name ,它會被映射為 String 的 Schema 類型,注冊時間 createTime 會被映射為 Date 的 Schema 類型。
允許的 Schema 類型有:( 了解更多 )
- String
- Number
- Date
- Buffer
- Boolean
- Mixed
- ObjectId
- Array
用法: -
自定義方法
模型的實例都是一個個的文檔,文檔中自帶許多方法。同時,我們也可以定義我們自己的方法。
var userSchema = new Schema({ name: String, pass: String, email: String, createTime: Date, lastLogin: Date, type: String }); //根據該用戶的類型區查找該類型下的所有用戶 userSchema.methods.findUsersByType = function(name, cb){ return this.find({type: this.type}, cb); } //新建模型 var User = mongoose.model('User', userSchema); //使用 var newUser = new User({...}); newUser.findUsersByType(function(err, users){ err && return console.error(err); console.log(users); })
這樣就向 User 的實例添加了一個自定義的方法。
-
靜態方法
同樣的,向模型中添加自定義方法也是很簡單。
userSchema.statics.findUsersByName = function(name, cb){ return this.find({name: new RegExp(name, "ig")}, cb); } //使用 User.findUsersByName('leung', function(err, users){ err && return console.error(err); console.log(users); })
-
查詢輔助
可以自定義一個查詢的輔助函數,它和實體的方法類似,但是供 Mongoose 查詢使用。
userSchema.query.byName = function(name){ return this.find({name: new RegExp(name, "ig")}); } //使用 userSchema.find().byName('leung').exec(function(err, users){ err && return console.error(err); console.log(users); })
-
索引
MongoDb 支持第二個索引,在使用 Mongoose 的時候,可以在定義 Schema 的時候定義索引。
//定義方法1 var userSchema = new Schema({ name: String, pass: String, email: String, createTime: {type: Date, index: true}, lastLogin: {type: Date, index: true}, type: String }); //定義方法2 userSchema.index({ createTime: 1, lastLogin: -1 });
Mongoose 會在程序啟動的時候,對于每個定義了索引的字段自動調用 ensureIndex 函數。當在不需要這些索引的時候,可以使用下列 4 種方式關閉索引。
mongoose.connect('mongodb://user:pass@localhost:port/database', { config: { autoIndex: false } }); // or mongoose.createConnection('mongodb://user:pass@localhost:port/database', { config: { autoIndex: false } }); // or userSchema.set('autoIndex', false); // or new Schema({..}, { autoIndex: false });
-
虛擬字段
虛擬字段可以讓你很方便的在文檔中存取,但是不會寫入數據庫中。getter 方法在格式化或者合并字段的時候很有用,而 setter 方法則在反格式化或者時將多個值合并的時候有用。
var personSchema = new Schema({ name:{ firstName: String, lastName: String } }); var Person = mongoose.model('Person', personSchema); //定義虛擬字段 fullName personSchema.virtual('name.fullName').get(function(){ console.log(this); return this.name.firstName + ' ' + this.name.lastName; }) var me = new Person({name: {firstName: 'zhong', lastName: 'Lueng'}}); console.log(me); console.log(me.name.fullName) //zhong Lueng
虛擬字段的 setter 方法會在其他校驗前使用,因此,即使字段時必須的,虛擬字段也會正常執行。
只用非虛擬字段才可以在查詢或者字段選擇中使用。
-
配置項
Schema 有許多可配置的配置項,可以在新建 Schema 時或者直接設置。
new Schema({..}, options); //or var schema = new Schema({..}); schema.set(option, value);
有效的配置項:
- autoIndex
- capped
- collection
- emitIndexErrors
- id
- _id
- minimize
- read
- safe
- shardKey
- strict
- toJSON
- toObject
- typeKey
- validateBeforeSave
- versionKey
- skipVersioning
- timestamps
具體的配置請移步至 官網
來自:http://jzleung.github.io/2016/08/13/mongoose-guide/