Mongoose學習javascript
由於網上關於mongoose的文檔有不少,可是都是分塊的沒有系統的總結,因此我總結網上的文章理出來一條思路,文檔中的不少內容都是從其餘文章中複製過來的,只做爲我的知識的學習,不會用於商用,在文章多處我也註明了出處html
MongoDB是一個開源的NoSQL數據庫,相比MySQL那樣的關係型數據庫,它更爲輕巧、靈活,很是適合在數據規模很大、事務性不強的場合下使用。java
Mongoose是封裝了MongoDB的操做的一個對象模型庫,爲nodejs而生。就好像咱們嫌原生javascript難寫,代碼量多,因而用jQuery庫同樣,由於MongoDB的操做接口複雜,不人性,因此有了Mongoose。這個庫徹底是可選的。node
內置類型git
String Number Date Buffer Boolean Mixed Objectid Arraygithub
用法實例數據庫
var schema = new Schema({ name: String, binary: Buffer, living: Boolean, updated: { type: Date, default: Date.now }, age: { type: Number, min: 18, max: 65 }, mixed: Schema.Types.Mixed, _someId: Schema.Types.ObjectId, array: [], ofString: [String], ofNumber: [Number], ofDates: [Date], ofBuffer: [Buffer], ofBoolean: [Boolean], ofMixed: [Schema.Types.Mixed], ofObjectId: [Schema.Types.ObjectId], nested: { stuff: { type: String, lowercase: true, trim: true } } }) // example use var Thing = mongoose.model('Thing', schema); var m = new Thing; m.name = 'Statue of Liberty'; m.age = 125; m.updated = new Date; m.binary = new Buffer(0); m.living = false; m.mixed = { any: { thing: 'i want' } }; m.markModified('mixed'); m._someId = new mongoose.Types.ObjectId; m.array.push(1); m.ofString.push("strings!"); m.ofNumber.unshift(1,2,3,4); m.ofDates.addToSet(new Date); m.ofBuffer.pop(); m.ofMixed = [1, [], 'three', { four: 5 }]; m.nested.stuff = 'good'; m.save(callback);
var schema = new mongoose.Schema({ name:{ type:'String', required: true, maxlength: 10, match: /^a/ }, date: { type: Date, default: Date.now }, age:{ type:'Number', min:18, //年齡最小18 max:120 //年齡最大120 }, city:{ type:'String', enum:['北京','上海'] //只能是北京、上海人 }, });
var userSchema = new Schema({ phone: { type: String, validate: { validator: function(v) { return /d{3}-d{3}-d{4}/.test(v); }, message: '{VALUE} is not a valid phone number!' } } }); var User = mongoose.model('user', userSchema); var u = new User(); u.phone = '555.0123'; // Prints "ValidationError: 555.0123 is not a valid phone number!" console.log(u.validateSync().toString()); u.phone = '201-555-0123'; // Prints undefined - validation succeeded! console.log(u.validateSync());
mongoose.model(modelName, schema)
var Blog = mongoose.model('Blog', blogSchema)
// 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); }
var Animal = mongoose.model('Animal', animalSchema); var dog = new Animal({ type: 'dog' }); dog.findSimilarTypes(function (err, dogs) { console.log(dogs); // woof });
// assign a function to the "statics" object of our animalSchema 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); });
var animalSchema = new Schema({ name: String, type: String, tags: { type: [String], index: true } // field level }); animalSchema.index({ name: 1, type: -1 }); // schema level
animalSchema.set('autoIndex', false); // or new Schema({..}, { autoIndex: false });
// define a schema var personSchema = new Schema({ name: { first: String, last: String } }); personSchema.virtual('name.full').get(function () { return this.name.first + ' ' + this.name.last; }); // compile our model var Person = mongoose.model('Person', personSchema); // create a document var bad = new Person({ name: { first: 'Walter', last: 'White' } }); console.log('%s is insane', bad.name.full); // Walter White is insane
bad.name.full = 'Breaking Bad'; personSchema.virtual('name.full').set(function (name) { var split = name.split(' '); this.name.first = split[0]; this.name.last = split[1]; }); ... mad.name.full = 'Breaking Bad'; console.log(mad.name.first); // Breaking console.log(mad.name.last); // Bad
new Schema({..}, options); // or var schema = new Schema({..}); schema.set(option, value);
document中間件支持如下document函數promise
query中間件支持如下model和query函數app
var mongoose = require('mongoose'); //引用mongoose模塊 var db = mongoose.createConnection('localhost','test'); //建立一個數據庫鏈接
db.on('error',console.error.bind(console,'鏈接錯誤:')); db.once('open',function(){ //一次打開記錄 });
var Tank = mongoose.model('Tank', yourSchema); var small = new Tank({ size: 'small' }); small.save(function (err) { if (err) return handleError(err); // saved! })
Model.create({ size: 'small' }, function (err, doc) { if (err) return handleError(err); // saved! }) const promise= Model.create(Doc) promise.then(function (result) { console.log(1111111111) console.log(result) },function (err) { console.log(2222222222) console.log(err) })
Model.update(conditions, doc, [options], [callback])
Tank.update({ _id: id }, { $set: { size: 'large' }}, function (err, raw) { if (err) return handleError(err); console.log('The raw response from Mongo was ', raw); });
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); }); });
Tank.findByIdAndUpdate(id, { $set: { size: 'large' }}, function (err, tank) { if (err) return handleError(err); res.send(tank); });
Tank.remove({ size: 'large' }, function (err) { if (err) return handleError(err); // removed! });
PersonModel.findOne({'name.last':'dragon'},'some select',function(err,person){ //若是err==null,則person就能取到數據 });
var query = PersonModel.findOne({'name.last':'dragon'}); query.select('some select'); query.exec(function(err,pserson){ //若是err==null,則person就能取到數據 });
Person .find({ occupation: /host/ }) .where('name.last').equals('Ghost') .where('age').gt(17).lt(66) .where('likes').in(['vaporizing', 'talking']) .limit(10) .sort('-occupation') .select('name occupation') .exec(callback);
一、本博客中的文章摘自網上的衆多博客,僅做爲本身知識的補充和整理,並分享給其餘須要的coder,不會用於商用。異步
二、由於不少博客的地址看完沒有及時作保存,因此不少不會在這裏標明出處,很是感謝各位大牛的分享,也但願你們理解。