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,不会用于商用。异步
二、由于不少博客的地址看完没有及时作保存,因此不少不会在这里标明出处,很是感谢各位大牛的分享,也但愿你们理解。