快速啟動
首先需要安裝MongoDB和Node.js。
然后使用npm下載mongoose:
npm install mongoose
接著我們直接在項目中引入mongoose,并且連接數據庫就會在本地運行 MongoDB了:
// index.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/demo');
用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:
var mySchema =new mongoose.Schema({name: String
});
我們創建了一個叫mySchema的Schema,并且定義了一個屬性name,限定類型是String。接著可以用mySchema創建一個Model:
var MyModel = mongoose.model('MyModel', mySchema);
這樣就按照mySchema創建了一個MyModel模型,這個MyModel其實充當了兩個作用:
充當MongoDB中的collection(集合)
是用來構造document(文檔)的類
所以要構造一條document只要:
var instance = new MyModel({ name: ' Instance' })
console.log( instance.name) // 'instance'
instance就是一條也可以稱作Document了。
如此看來Schema、Model和Document的關系就像是抽象類、實現類和實例三者的關系一樣。所以嘛,自然可以在Schema定義后添加方法:
var mySchema =new mongoose.Schema({name: String
});
mySchema.methods.getName=function(){console.log(this.name + "來自getName方法");
}
...instance.getName();//'instance來自getName方法'
instance實例現在還沒有被保存在MongoDB中,所有的實例都要調用save方法后才會保存進數庫:
instance.save((err,instance)=>{if (err) return console.error(err);instance.getName();
})
而后,需要查詢數據時就需要使用Model,因為Model的作用時充當MongoDB中的collection(集合),所以這樣查詢數據:
MyModel.find(function (err, instances) {if (err) return console.error(err);console.log(instances);
});
當然了,也可以加條件查詢:
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');
Schemas
定義schema
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有:
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array
創建了Schema后肯定就是創建Model了,然而,在這之間我們還可以定義instance方法、定義靜態Model方法、定義索引和使用生命周期掛鉤(中間件)
instance方法
instance方法使用schema的methods添加,這樣做可以讓創建的documents在save之前執行一些自定義的操作:
// define a schema
var animalSchema = new Schema({ name: String, type: String });// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {return this.model('Animal').find({ type: this.type }, cb);
}//define a model
var Animal = mongoose.model('Animal', animalSchema);//instance
var dog = new Animal({ type: 'dog' });
dog.findSimilarTypes(function (err, dogs) {console.log(dogs); // woof
});
這樣做要注意的是不要重寫mongoose原來的document方法,不然會有未知錯誤。
靜態Model方法
在methods上添加的是給document用的,而在statics上添加的方法就是給Model用的:
// assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function (name, cb) {this.find({ name: new RegExp(name, 'i') }, cb);
}
var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {console.log(animals);
});
索引
MongoDB支持使用索引。在mongoose中,分別可以在內部和外部定義,不過復合索引就只能在外部定義了:
var animalSchema = new Schema({name: String,type: String,tags: { type: [String], index: true } // 內部
});
animalSchema.index({ name: 1, type: -1 }); // 外部,復合索引
當應用啟動,Mongoose就會自動調用ensureIndex為每個schema創建索引。索引創建會有顯著的性能影響,所以建議在生產環境中禁用:
animalSchema.set('autoIndex', false);
// or
new Schema({..}, { autoIndex: false });
虛擬屬性
虛擬屬性是一種不會存儲進數據庫但是存在在doucment中的屬性。充當getter和setter的功能。
基本代碼:
var personSchema = new Schema({name: {first: String,last: String}
});
// compile our model
var Person = mongoose.model('Person', personSchema);
// create a document
var bad = new Person({name: { first: 'Walter', last: 'White' }
});
當調用toObject和toJSON方法時默認都是不會有虛擬屬性的。
現在想訪問bad.name.full就給出全名,就要使用虛擬屬性的getter功能:
personSchema.virtual('name.full').get(function () {return this.name.first + ' ' + this.name.last;
});。。。console.log('%s is insane', bad.name.full); // Walter White is insane
同樣的有setter功能:
personSchema.virtual('name.full').set(function (name) {var split = name.split(' ');this.name.first = split[0];this.name.last = split[1];
});
...
bad.name.full = 'Breaking Bad';
console.log(bad.name.first); // Breaking
console.log(bad.name.last); // Bad
options
Schemas在構建實例或者通過set方法可以進行有options的配置:
new Schema({..}, options);
// 或者
var schema = new Schema({..});
schema.set(option, value);
options:
autoIndex:自動索引
capped
collection
id
_id
read
safe
shardKey
strict
toJSON
toObject
versionKey
autoIndex
在應用啟動時,Mongoose會調用ensureIndex為Schema構建索引。自Mongoose v3起,索引默認都會在后臺創建。如果想關閉自動創建或者以后手動創建索引,可以進行如下設置:
var schema = new Schema({..}, { autoIndex: false });
var Clock = mongoose.model('Clock', schema);
Clock.ensureIndexes(callback);
bufferCommands
capped
Mongoose支持MongoDB的固定大小集合,直接設置capped表示最大空間,單位時bytes,當然也可以使用對象設置max(最大document數)和autoIndexId:
new Schema({..}, { capped: 1024 });
//或者
new Schema({..}, { capped: { size: 1024, max: 1000, autoIndexId: true } });
collection
Mongoose中collection的名字默認時注冊Model時的名字,如果想要自定義,可以這樣設置:
var dataSchema = new Schema({..}, { collection: 'data' });
id
document都會設置一個虛擬屬性id并配置getter來獲取_id,如果不想要id虛擬屬性可以設為false:
// default behavior
var schema = new Schema({ name: String });
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p.id); // '50341373e894ad16347efe01'
// disabled id
var schema = new Schema({ name: String }, { id: false });
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p.id); // undefined
_id
Mongoose默認會在生成document的時候生成_id字段,如果想禁止這個行為可以設為false,但是插入數據庫的時候仍然會有_id字段:
// default behavior
var schema = new Schema({ name: String });
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p); // { _id: '50341373e894ad16347efe01', name: 'mongodb.org' }
// disabled _idvar schema = new Schema({ name: String }, { _id: false });
// 不要使用schema.set("_id",false),
var Page = mongoose.model('Page', schema);
var p = new Page({ name: 'mongodb.org' });
console.log(p); // { name: 'mongodb.org' }
// MongoDB 會在數據被插入的時候給_id
p.save(function (err) {if (err) return handleError(err);Page.findById(p, function (err, doc) {if (err) return handleError(err);console.log(doc); // { name: 'mongodb.org', _id: '50341373e894ad16347efe12' }})
})
read
設置讀寫分離屬性:
var schema = new Schema({..}, { read: 'primary' }); // also aliased as 'p'
var schema = new Schema({..}, { read: 'primaryPreferred' }); // aliased as 'pp'
var schema = new Schema({..}, { read: 'secondary' }); // aliased as 's'
var schema = new Schema({..}, { read: 'secondaryPreferred' }); // aliased as 'sp'
var schema = new Schema({..}, { read: 'nearest' }); // aliased as 'n'
safe
shardKey
strict
mongoose默認會開啟嚴格模式,所有不是在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 thingSchema = new Schema({..})
var Thing = mongoose.model('Thing', thingSchema);
var thing = new Thing({},false);
thing.iAmNotInTheSchema = true;
thing.save(); // iAmNotInTheSchema is never saved to the db
toJSON和toObject
兩個方法類似,都是輸出格式化對象:
var schema = new Schema({ name: String });
schema.path('name').get(function (v) {return v + ' is my name';
});//默認是不使用getter和不輸出virtual
schema.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內部會調用toJSON
console.log(JSON.stringify(m));//console內部時調用toObject
console.log(m);
versionKey
設置document的version鍵,默認鍵是_v,設為false的話就沒有這個version:
var schema = new Schema({ name: 'string' });
var Thing = mongoose.model('Thing', schema);
var thing = new Thing({ name: 'mongoose v3' });
thing.save(); // { __v: 0, name: 'mongoose v3' }
// 換 versionKey
new Schema({..}, { versionKey: '_somethingElse' })
var Thing = mongoose.model('Thing', schema);
var thing = new Thing({ name: 'mongoose v3' });
thing.save(); // { _somethingElse: 0, name: 'mongoose v3' }
//設為false
new Schema({..}, { versionKey: false });
var Thing = mongoose.model('Thing', schema);
var thing = new Thing({ name: 'no versioning please' });
thing.save(); // { name: 'no versioning please' }
Models
Models在Schema和document中作承上啟下,作用有兩個:
- 充當MongoDB中的collection(集合)
- 是用來構造document(文檔)的類
所以document的創建和檢索都是來自于Models的方法。
第一個model
var schema = new mongoose.Schema({ name: 'string', size: 'string' });
var Tank = mongoose.model('Tank', schema);
構造documents
var Tank = mongoose.model('Tank', yourSchema);
var small = new Tank({ size: 'small' });
small.save(function (err) {if (err) return handleError(err);// saved!
})
// or
Tank.create({ size: 'small' }, function (err, small) {if (err) return handleError(err);// saved!
})
查詢
查詢操作有諸如find, findById, findOne, 和 where等方法,直接查API:
Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback);
移除
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);
Documents
如果說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:
var Parent = mongoose.model('Parent', parentSchema);
var parent = new Parent({ children: [{ name: 'Matt' }, { name: 'Sarah' }] })
parent.children[0].name = 'Matthew';
parent.save(callback);//保存后數據庫中只有Parent集合var doc = parent.children.id(id);//使用`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 comment
parent.children.push({ name: 'Liesl' });
var subdoc = parent.children[0];
console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true
parent.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` fields
Person.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` fields
query.select('name occupation');
// execute the query at a later time
query.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方法自定義驗證規則:
var toySchema = new Schema({color: String,name: String
});
var Toy = mongoose.model('Toy', toySchema);
//自定義驗證規則
Toy.schema.path('color').validate(function (value) {return /blue|green|white|red|orange|periwinkle/i.test(value);
}, 'Invalid color');
var toy = new Toy({ color: 'grease'});
toy.save(function (err) {// err is our ValidationError object// err.errors.color is a ValidatorError objectconsole.log(err.errors.color.message) // prints 'Validator "Invalid color" failed for path color with value `grease`'console.log(String(err.errors.color)) // prints 'Validator "Invalid color" failed for path color with value `grease`'console.log(err.errors.color.type) // prints "Invalid color"console.log(err.errors.color.path) // prints "color"console.log(err.errors.color.value) // prints "grease"console.log(err.name) // prints "ValidationError"console.log(err.message) // prints "Validation failed"
});
驗證錯誤觸發后,document會有一個errors屬性:
toy.errors.color.message === err.errors.color.message
中間件
Mongoose允許在文檔的init,validate,save和remove的前后觸發一些方法
Pre
前置有兩種形式,串行和并行。
串行
var schema = new Schema(..);
schema.pre('save', function (next) {// 中間件一個接一個next();
});
并行
var schema = new Schema(..);
schema.pre('save', true, function (next, done) {// 異步執行中間件next();doAsync(done);
});
錯誤傳遞
pre可以將傳遞錯誤:
schema.pre('save', function (next) {var err = new Error('something went wrong');next(err);
});
// later...
myDoc.save(function (err) {console.log(err.message) // something went wrong
});
Post
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");});
/*console
pre save
after pre save
post save
save
*/
Population
MongoDB是文檔型數據庫,所以沒有關系型數據庫joins(數據庫的兩張表通過”外鍵”,建立連接關系。) 特性。建立數據關聯時會非常麻煩,Mongoose就封裝了Population實現document中填充其他collection的document。
建立關聯
能建立關聯的字段只有ObjectId, Number, String, and Buffer四種類型可以。建立關聯只需要在聲明Schema的時候使用ref屬性就可以關聯:
var mongoose = require('mongoose'), Schema = mongoose.Schemavar personSchema = Schema({_id : Number,name : String,age : Number,stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({_creator : { type: Number, ref: 'Person' },title : String,fans : [{ type: Number, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
storySchema中_creator和fans字段都關聯了Person,并且都將type設為Number。這是因為,Person和Story建立了關聯后,Story中的document的_creator或fans字段是通過Person的_id屬性關聯對應數據的,所以Story的_creator和fans要與Person的_id類型保持一致。
保存refs
要先保存被關聯的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聲明關聯字段就會進行關聯查詢的:
Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {if (err) return handleError(err);console.log('The creator is %s', story._creator.name);// prints "The creator is Aaron"
})
_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()
Plugins
Schemas允許添加插件,這樣就會想繼承一樣,每個Schemas都會有插件中定義的功能:
// lastMod.js
module.exports = exports = function lastModifiedPlugin (schema, options) {schema.add({ lastMod: Date })schema.pre('save', function (next) {this.lastMod = new Datenext()})if (options && options.index) {schema.path('lastMod').index(options.index)}
}// game-schema.js
var lastMod = require('./lastMod');
var Game = new Schema({ ... });
Game.plugin(lastMod, { index: true });// player-schema.js
var lastMod = require('./lastMod');
var Player = new Schema({ ... });
Player.plugin(lastMod);
Game和Player就都會有lastMod中定義的功能。
版權聲明:本文為CSDN博主「weixin_36743929」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_36743929/article/details/54883146