Mongoose是什么
Mongoose是MongoDB的一个对象模型工具,能够工做于异步环境下。css
定义一个模型很容易:git
var Comments = new Schema({ title : String , body : String , date : Date});var BlogPost = new Schema({ author : ObjectId , title : String , body : String , date : Date , comments : [Comments] , meta : { votes : Number , favs : Number }});mongoose.model('BlogPost', BlogPost);
安装
推荐经过NPM方式安装:github
$ npm install mongoose
或者,你能够从Github仓库中获取代码,而后解压:mongodb
$ git clone git@github.com:LearnBoost/mongoose.git support/mongoose/
// 将模块添加至NodeJS能够找到的环境路径中require.paths.unshift('support/mongoose/lib');
而后就能够在应用中将mongoose模块包含进来数据库
require('mongoose');
链接到MongoDB数据库
首先,咱们须要定义一个链接。若是你的应用只使用一个数据库,可使用mongoose.connect,若是须要建立附加数据库链接,使用mongoose.createConnection。npm
connect和createConnection都能链接mongodb数据库,支持以URI或参数(host,database,port)的形式。api
var mongoose = require('mongoose');mongoose.connect('mongodb://www.csser.com/csser.com_database');
链接一旦创建成功,该链接实例的open事件就被触发。若是你使用的是mongoose.connect方式,链接对象为mongoose.connection;不然,mongoose.createConnection返回的是Connection对象。缓存
切记!Mongoose在与数据库真正创建链接以前便缓存了全部的命令,这就意味着你在定义模型、执行查询时没必要非要确认与MongoDB数据库的链接是否已经创建。(一回@CSSer注:异步是MongoDB等与传统数据库的重大区别)异步
定义模型
模型是经过模式接口(Schema interface)定义的,如:mongoose
var Schema = mongoose.Schema , ObjectId = Schema.ObjectId;var BlogPost = new Schema({ author : ObjectId , title : String , body : String , date : Date});
除了定义文档结构和你要存储的数据类型外,模式(Schema)还用于如下定义:
- Validators (异步和同步)
- Defaults - 默认值
- Getters
- Setters
- Indexes - 索引
- Middleware - 中间件
- Methods definition - 方法定义
- Statics definition - 静态定义
- Plugins - 插件
下面的代码向咱们展现了这些功能的一部分:
var Comment = new Schema({ name : { type: String, default: 'hahaha' } , age : { type: Number, min: 18, index: true } , bio : { type: String, match: /[a-z]/ } , date : { type: Date, default: Date.now }});// 定义setterComment.path('name').set(function (v) { return v.capitalize();});// 定义中间件Comment.pre('save', function (next) { notify(this.get('email')); next();});
你能够查看几乎包含全部模型定义的 示例 。
访问模型
当经过mongoose.model('ModelName', mySchema)定义了一个模型以后,咱们能够经过相同的函数来访问它:
var myModel = mongoose.model('ModelName');
接下来咱们能够将模型的实例保存下来:
var instance = new myModel();instance.my.key = 'csser';instance.save(function (err) { //});
或者咱们也能够从一样的的集合(collection)中找到文档(documents):
myModel.find({}, function (err, docs) { // docs.forEach});
也能够调用findOne, findById, update等等方法,更多的细节请阅读 API文档 。
嵌入文档
还记得在第一个示例的代码片断中,咱们在模式中定义了一个键(key):
comments: [Comments]
这里的Comments是咱们已经建立的模式(Schema),这就是说建立嵌入文档跟下面的代码看起来同样简单:
// 从新得到模型var BlogPost = mongoose.model('BlogPost');// 建立一篇博客日志var post = new BlogPost();// 建立一个评论post.comments.push({ title: 'My comment for csser.com' });post.save(function (err) { if (!err) console.log('Success!');});
用一样的方式删除模式:
BlogPost.findById(myId, function (err, post) { if (!err) { post.comments[0].remove(); post.save(function (err) { // do something }); }});
嵌入文档拥有与模型相同的功能,包括Defaults、validators、middleware等。当发生错误时,它会冒泡到save()错误回调函数,这里错误处理是一个单元。
Mongoose interacts with your embedded documents in arrays atomically, out of the box.
中间件
中间件是Mongoose 1.0推出的最激动人心的功能之一,它让咱们能够不用再受嵌套回调函数的折磨了。
中间件定义在模式级别(Schema level),当方法初始化时(文档与MongoDB数据初始化后)、保存数据时(文档或嵌入文档保存后)生效。
中间件有两种类型,它们由定义的函数签名肯定(即函数接受的参数)。
顺序(Serial)中间件定义以下:
.pre(method, function (next) { // ... })
当每一个中间件调用下一个时,它们按顺序执行。
并行(Parallel)中间件提供更细粒度的控制,其定义以下:
.pre(method, function (next, done) { // ... })
Parallel 中间件能够马上next(),可是只有当全部parallel中间件调用done()以后最后的参数才被执行。
错误处理
若是任一个中间件调用next或done时抛出了错误,执行流会中断,错误会被做为参数传入回调函数。
例如:
schema.pre('save', function (next) { // 发生了一些错误 next(new Error('有错误发生'));});// 接着...myModel.save(function (err) { // 错误能够来自某个中间件});
API 文档
能够在 http://mongoosejs.com 找到相关API文档。