首先需要安裝MongoDB和Node.js。 然后使用npm下載mongoose: npm install mongoose
接著我們直接在項目中引入mongoose
,并且連接數據庫就會在本地運行 MongoDB
了:
用node命令執行index.js,demo數據庫就會在本地運行了。我們需要在連接數據庫成功或者失敗的時候有些提示,可以這樣添加代碼:
var db = mongoose.connection;db.on('error', console.error.bind(console, 'connection error:'));db.once('open', function (callback) { // 后續代碼默認都寫在這里!});連接成功的時候就會執行一次回調函數,現在假設下面所有代碼都是在成功的回調函數中的。
在Mongoose
中,所有東西都是衍生自Schema
。 Schema(模式)
就像是Model(模型)
的抽象類一樣的存在,創建一個Schema
:
我們創建了一個叫mySchema
的Schema
,并且定義了一個屬性name
,限定類型是String
。接著可以用mySchema
創建一個Model
:
這樣就按照mySchema
創建了一個MyModel
模型,這個MyModel
其實充當了兩個作用:
所以要構造一條document
只要:
instance
就是一條也可以稱作Document
了。
如此看來Schema
、Model
和Document
的關系就像是抽象類、實現類和實例三者的關系一樣。所以嘛,自然可以在Schema
定義后添加方法:
instance
實例現在還沒有被保存在MongoDB中,所有的實例都要調用save
方法后才會保存進數庫:
而后,需要查詢數據時就需要使用Model
,因為Model的作用時充當MongoDB中的collection(集合)
,所以這樣查詢數據:
當然了,也可以加條件查詢:
MyModel.find({name:"instance"},callback);這樣就是一個完整的使用mongoose插入和查詢數據的操作了。完整代碼如下:
var mongoose = require('mongoose');var db = mongoose.connection;db.on('error', console.error.bind(console, 'connection error:'));db.once('open', function(callback) { var mySchema =new mongoose.Schema({ name: String }); mySchema.methods.getName = function() { console.log(this.name + "來自getName方法"); } var MyModel = mongoose.model('MyModel', mySchema); var instance = new MyModel({ name: ' Instance' }) console.log(instance.name) // 'instance' instance.getName(); //'instance' instance.save((err, instance) => { if (err) { return console.error(err) }; instance.getName(); })});mongoose.connect('mongodb://localhost/test');Mongoose所有的一切始于Schema。每一個Schema都映射到MongoDB中的collection(集合)和定義了document(文檔)的結構。
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
以后添加額外的key
,可以使用Schema的add
方法。
現在只需要知道SchemaTypes有:
StringNumberDateBufferBooleanMixedObjectIdArray創建了Schema
后肯定就是創建Model
了,然而,在這之間我們還可以定義instance方法、定義靜態Model方法、定義索引和使用生命周期掛鉤(中間件)
instance方法使用schema
的methods
添加,這樣做可以讓創建的documents在save之前執行一些自定義的操作:
這樣做要注意的是不要重寫mongoose原來的document方法,不然會有未知錯誤。
在methods
上添加的是給document用的,而在statics
上添加的方法就是給Model用的:
MongoDB支持使用索引。在mongoose中,分別可以在內部和外部定義,不過復合索引就只能在外部定義了:
var animalSchema = new Schema({ name: String, type: String, tags: { type: [String], index: true } // 內部});animalSchema.index({ name: 1, type: -1 }); // 外部,復合索引當應用啟動,Mongoose就會自動調用ensureIndex
為每個schema創建索引。索引創建會有顯著的性能影響,所以建議在生產環境中禁用:
虛擬屬性是一種不會存儲進數據庫但是存在在doucment中的屬性。充當getter
和setter
的功能。 基本代碼:
當調用toObject和toJSON方法時默認都是不會有虛擬屬性的。 現在想訪問bad.name.full
就給出全名,就要使用虛擬屬性的getter
功能:
同樣的有setter
功能:
Schemas在構建實例或者通過set
方法可以進行有options的配置:
options:
autoIndex:自動索引cappedcollectionid_idreadsafeshardKeystricttoJSONtoObjectversionKey
在應用啟動時,Mongoose會調用ensureIndex為Schema構建索引。自Mongoose v3起,索引默認都會在后臺創建。如果想關閉自動創建或者以后手動創建索引,可以進行如下設置:
var schema = new Schema({..}, { autoIndex: false });var Clock = mongoose.model('Clock', schema);Clock.ensureIndexes(callback);Mongoose支持MongoDB的固定大小集合,直接設置capped
表示最大空間,單位時bytes
,當然也可以使用對象設置max
(最大document數)和autoIndexId
:
Mongoose中collection的名字默認時注冊Model時的名字,如果想要自定義,可以這樣設置:
var dataSchema = new Schema({..}, { collection: 'data' });document
都會設置一個虛擬屬性id
并配置getter
來獲取_id
,如果不想要id
虛擬屬性可以設為false
:
Mongoose默認會在生成document的時候生成_id
字段,如果想禁止這個行為可以設為false
,但是插入數據庫的時候仍然會有_id
字段:
設置讀寫分離屬性:
var schema = new Schema({..}, { read: 'safemongoose默認會開啟嚴格模式,所有不是在Schema定義的屬性都不會被保存進數據庫,將strict設為false就會:
var thingSchema = new Schema({..})var Thing = mongoose.model('Thing', thingSchema);var thing = new Thing({ iAmNotInTheSchema: true });thing.save(); // iAmNotInTheSchema不會保存進數據庫// 設為 false..var thingSchema = new Schema({..}, { strict: false });var thing = new Thing({ iAmNotInTheSchema: true });thing.save(); // iAmNotInTheSchema會保存進數據庫還支持在instance的時候設置:
var thing = new Thing(doc, false); // 關閉嚴格模式除了boolean,也可以設置為throw
,但是這樣會拋出錯誤,而不時忽略值。 提示:不要手賤設為false 提示:在mongoose v2 默認只時false 提示:直接在document上set的只都不會被保存
兩個方法類似,都是輸出格式化對象:
var schema = new Schema({ name: String });schema.path('name').get(function (v) { return v + ' is my name';});//默認是不使用getter和不輸出virtualschema.set('toJSON', { getters: true, virtuals: false });var M = mongoose.model('Person', schema);var m = new M({ name: 'Max Headroom' });console.log(m.toObject()); // { _id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom' }console.log(m.toJSON()); // { _id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom is my name' }// stringify內部會調用toJSONconsole.log(JSON.stringify(m));//console內部時調用toObjectconsole.log(m);設置document的version鍵,默認鍵是_v
,設為false的話就沒有這個version:
Models在Schema和document中作承上啟下,作用有兩個: - 充當MongoDB中的collection(集合) - 是用來構造document(文檔)的類 所以document的創建和檢索都是來自于Models的方法。
查詢操作有諸如find
, findById
, findOne
, 和 where
等方法,直接查API:
Models有個remove方法可以用于移除指定條件的documents:
Tank.remove({ size: 'large' }, function (err) { if (err) return handleError(err); // removed!});Models有個update方法可以用于更新指定條件的documents:
let query = { age: { $gt: 18 } };//查詢條件let updated = { oldEnough: true };//更新結果 也可以是{ $set: { name: 'jason borne' }}MyModel.update(query,updated ,options, fn);如果說Models(也就為collection)相當于SQL數據庫中的表的話,那么Document就相當于行了。
數據的更新操作也可以直接使用在document:
Tank.findById(id, function (err, tank) { if (err) return handleError(err); tank.size = 'large'; tank.save(function (err) { if (err) return handleError(err); res.send(tank); });});在構建Schema可以使用另外一個Schema作為數據類型:
var childSchema = new Schema({ name: 'string' });var parentSchema = new Schema({ children: [childSchema]})保存文檔的時候,子文檔在數據庫并不會獨自使用集合保存,數據庫中保存的只有父文檔的集合。不過每個子文檔都會有一個_id
:
但是子文檔如果的生命周期有掛鉤的話也是會執行的:
childSchema.pre('save', function (next) { if ('invalid' == this.name) return next(new Error('#sadpanda')); next();});var parent = new Parent({ children: [{ name: 'invalid' }] });parent.save(function (err) { console.log(err.message) // #error : sadpanda})MongooseArray方法有想 push, unshift, addToSet等等可以添加子文檔:
var Parent = mongoose.model('Parent');var parent = new Parent;// create a commentparent.children.push({ name: 'Liesl' });var subdoc = parent.children[0];console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }subdoc.isNew; // trueparent.save(function (err) { if (err) return handleError(err) console.log('Success!');});//或者var newdoc = parent.children.create({ name: 'Aaron' });移除子文檔可以使用remove方法:
var doc = parent.children.id(id).remove();parent.save(function (err) { if (err) return handleError(err); console.log('the sub-doc was removed')});在v3版本允許直接聲明對象聲明子文檔:
var parentSchema = new Schema({ children: [{ name: 'string' }]})所有model的查詢操作都會有兩種形式: - 當有回調方法作為參數時:會將查詢操作的結果傳遞給回調方法; - 當沒有回調方法作為參數時:會將查詢結果封裝成一個QueryBuilder接口返回。 先看看有回調方法是怎樣的:
var Person = mongoose.model('Person', yourSchema);// find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fieldsPerson.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) { if (err) return handleError(err); console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host.})在Mongoose中的查詢回調方法的形式都類似于:callback(error, result)
。result不一定都是document的list,要看具體是什么操作。
再來看看沒有回調函數的寫法:
// find each person with a last name matching 'Ghost'var query = Person.findOne({ 'name.last': 'Ghost' });// selecting the `name` and `occupation` fieldsquery.select('name occupation');// execute the query at a later timequery.exec(function (err, person) { if (err) return handleError(err); console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host.})//也可以使用鏈式操作Person.findOne({ 'name.last': 'Ghost' }).select('name occupation').exec(callback);上面三種寫法是做同一件事情,不加回調參數時,要使用exec
才會執行所有操作。
Mongoose有幾個內置的驗證器: - 所有的 SchemaTypes 都可以聲明required
; - Nembers 有 min
和max
; - String有enum
和match
驗證。 所有的這些都可以在 Schema創建時進行聲明。
用戶還可以使用validate
方法自定義驗證規則:
驗證錯誤觸發后,document會有一個errors屬性:
toy.errors.color.message === err.errors.color.messageMongoose允許在文檔的init
,validate
,save
和remove
的前后觸發一些方法
前置有兩種形式,串行和并行。
pre
可以將傳遞錯誤:
Post中間件是在指定操作完成后,回調函數還沒有執行前執行的方法:
parentSchema.pre("save", function(next, done) { console.log("pre save"); next(); console.log("after pre save"); })parentSchema.post("save", function() { console.log("post save"); })...parent.save(function(err) { if (err) { console.log(err); return; } console.log("save"); });/*consolepre saveafter pre savepost savesave*/MongoDB是文檔型數據庫,所以沒有關系型數據庫joins(數據庫的兩張表通過”外鍵”,建立連接關系。) 特性。建立數據關聯時會非常麻煩,Mongoose就封裝了Population實現document中填充其他collection的document。
能建立關聯的字段只有ObjectId, Number, String, and Buffer四種類型可以。建立關聯只需要在聲明Schema的時候使用ref
屬性就可以關聯:
storySchema中_creator和fans字段都關聯了Person,并且都將type設為Number。這是因為,Person和Story建立了關聯后,Story中的document的_creator或fans字段是通過Person的_id屬性關聯對應數據的,所以Story的_creator和fans要與Person的_id類型保持一致。
要先保存被關聯的document(Person),并且將_id注冊進去:
var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });aaron.save(function (err) { if (err) return handleError(err); var story1 = new Story({ title: "Once upon a timex.", _creator: aaron._id // 這里可以直接用aaron }); story1.save(function (err) { if (err) return handleError(err); // thats it! });})當然了注冊的時候直接寫個0
也可以,這個ref只是在檢索Person的_id字段的依據的時候。
現在只需要在關聯查詢的時候使用populate
聲明關聯字段就會進行關聯查詢的:
_creator
字段就會被關聯document給替換了。數組也是同樣的道理,每個元素都會被相應的document給替換。
可以對被關聯的document進行篩選:
Story.findOne({ title: /timex/i }).populate('_creator', 'name') // 只返回name字段.exec(function (err, story) { if (err) return handleError(err); console.log('The creator is %s', story._creator.name); // prints "The creator is Aaron" console.log('The creators age is %s', story._creator.age); // prints "The creators age is null'})在3.6版本后可以使用空格分割populate:
Story.find(...).populate('fans author') //使用空格分開.exec()但是在3.6之前就只能鏈式操作:
Story.find(...).populate('fans').populate('author').exec()查詢的時候可以使用其他參數:
Story.find(...).populate({ path: 'fans', match: { age: { $gte: 21 }}, select: 'name -_id', options: { limit: 5 }}).exec()Schemas允許添加插件,這樣就會想繼承一樣,每個Schemas都會有插件中定義的功能:
// lastMod.jsmodule.exports = exports = function lastModifiedPlugin (schema, options) { schema.add({ lastMod: Date }) schema.pre('save', function (next) { this.lastMod = new Date next() }) if (options && options.index) { schema.path('lastMod').index(options.index) }}// game-schema.jsvar lastMod = require('./lastMod');var Game = new Schema({ ... });Game.plugin(lastMod, { index: true });// player-schema.jsvar lastMod = require('./lastMod');var Player = new Schema({ ... });Player.plugin(lastMod);Game和Player就都會有lastMod中定義的功能。
新聞熱點
疑難解答