前言
Mongoose 是在nodejs環境下,對mongodb進行便捷操作的對象模型工具。本文介紹解(翻)密(譯)Mongoose插件。
Schema
開始我們就要講到Schema,一個Schema對應的是mongodb的collection(相當于SQL table),并且定義其結構。
var mongoose = require('mongoose');var Schema = mongoose.Schema;//定義一個博客結構var blogSchema = new Schema({ title: String, author: String, body: String, comments: [{ body: String, date: Date }], date: { type: Date, default: Date.now }, hidden: Boolean, meta: { votes: Number, favs: Number } });Schema可用Type:
.String (ex: 'ABCD')
.Number (ex: 123)
.Date (ex: new Date)
.Buffer (ex: new Buffer(0))
.Boolean (ex: false)
.Schema.Types.Mixed (ex: {any:{thing:'ok'}})
.Schema.Types.ObjectId (ex:new mongoose.Types.ObjectID)
.Array (ex:[1,2,3])
.Schema.Types.Decimal128
.Map (ex: new Map([['key','value']]))
我們可以通過一段代碼,將Schema轉化成Model: mongoose.model(modelName,Schema)
var Blog = mongoose.model('Blog', blogSchema);賦予Schema方法,當方法轉成Model的時候,會將方法給予Model
//創建一個變量,Schemavar animalSchema = new Schema({ name: String, type: String });//將方法賦予這個SchemaanimalSchema.methods.findSimilarTypes = function(cb) { return this.model('Animal').find({ type: this.type }, cb);};var Animal = mongoose.model('Animal', animalSchema);var dog = new Animal({ type: 'dog' });dog.findSimilarTypes(function(err, dogs) { console.log(dogs); // woof});在Schema方法里,不要使用箭頭函數,它會重新綁定this。
賦予Schema static (靜態)方法,我們繼續使用上面的例子:
//賦予靜態方法,可以再Model不實例化的情況下調用animalSchema.statics.findByName = function(name, cb) { return this.find({ name: new RegExp(name, 'i') }, cb);};var Animal = mongoose.model('Animal', animalSchema);Animal.findByName('fido', function(err, animals) { console.log(animals);});Schema索引 index
MongoDB支持二級索引,在mongoose,我們可以將索引定在Schema層。
var animalSchema = new Schema({ name: String, type: String, tags: { type: [String], index: true } // 聲明在字段層});animalSchema.index({ name: 1, type: -1 }); // 聲明在使用index(二級索引)的時候記得要disable Mongodb 的 autoIndex。
mongoose.connect('mongodb://user:pass@localhost:port/database', { autoIndex: false }); // 或者mongoose.createConnection('mongodb://user:pass@localhost:port/database', { autoIndex: false }); // 或者animalSchema.set('autoIndex', false); // 或者new Schema({..}, { autoIndex: false });虛擬化
// 聲明一個Schemavar personSchema = new Schema({ name: { first: String, last: String }});// 轉成Modelvar Person = mongoose.model('Person', personSchema);// 實例化Modelvar axl = new Person({ name: { first: 'Axl', last: 'Rose' }});//1.如果我們想要打印Person的姓名console.log(axl.name.first + ' ' + axl.name.last); // Axl Rose//2.使用虛擬化,我們聲明一個虛擬字段,然后通過get給其賦值personSchema.virtual('fullName').get(function () { return this.name.first + ' ' + this.name.last;});console.log(axl.fullName); // Axl Rose
新聞熱點
疑難解答
圖片精選