什么是Mongoose
Mongoose库简而言之就是对node环境中MongoDB数据库操作的封装,一种对象模型工具,可以将数据库中的数据转换为JavaScript对象供我们使用。
- 官方API
- windows环境部署mongodb
- ubuntu环境部署mongodb
模式、模型
Schema(模式)
一种以文件形式存储的数据库模型骨架,不具备数据库的操作能力,仅仅只是一段代码,无法通往数据库端, 仅仅只是数据库模型在程序片段中的一种表现
var BlogSchema = new Schema({title:String,author:String
});
复制代码
-
Schema.Type
Schema.Type是由Mongoose内定的一些数据类型,基本数据类型都在其中,Mongoose也内置了一些特有的Schema.Type
var ExampleSchema = new Schema({name:String,binary:Buffer,living:Boolean,updated:Date,age:Number,mixed:Schema.Types.Mixed, //该混合类型等同于nested_id:Schema.Types.ObjectId, //主键_fk:Schema.Types.ObjectId, //外键array:[],arrOfString:[String],arrOfNumber:[Number],arrOfDate:[Date],arrOfBuffer:[Buffer],arrOfBoolean:[Boolean],arrOfMixed:[Schema.Types.Mixed],arrOfObjectId:[Schema.Types.ObjectId]}); 复制代码
Model(模型)
Model模型,是经过Schema构造来的,是Schema的编译版本。一个model的实例直接映射为数据库中的一个文档。基于这种关系, 以后的增删改查(CURD)都要通过这个Model实现。
//先创建Schema
var UserSchema = new Schema({name:'String',sex:'String'
});
//通过Schema创建Model
var UserModel = mongoose.model('User',UserSchema );
复制代码
查询
直接查询
PersonModel.findOne({'name.last':'dragon'},function(err,person){});
复制代码
###链式查询 这种方式相对直接查询,分的比较明细,如果不带callback,则返回query,该query对象执行的方法都将返回自己,只有在执行exec方法时才执行查询,而且必须有回调。
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);
复制代码
##验证Validation 数据的存储是需要验证的,不是什么数据都能往数据库里丢或者显示到客户端的,如果验证失败,则会返回err。
1.required 非空验证
2.min/max 范围验证(边值验证)
3.enum/match 枚举验证/匹配验证
4.validate 自定义验证规则
var PersonSchema = new Schema({name:{type:'String',required:true //姓名非空},age:{type:'Nunmer',min:18, //年龄最小18max:120 //年龄最大120},city:{type:'String',enum:['北京','上海'] //只能是北京、上海人},other:{type:'String',validate:[validator,err] //validator是一个验证函数,err是验证失败的错误信息}
});
复制代码
使用初步
安装文件
npm install mongoose --save
复制代码
引入依赖
var mongoose = require("mongoose")
mongoose.connect('mongodb://localhost/testDataBase');
复制代码
定义schema
这里我们定义一个userSchema.js文件
var mongoose = require('mongoose');
var Schema = mongoose.Schema;var UserSchema = new Schema({uid: {type: String,required: true, unique: true},logLevel: {type: String,default: 'info'},meta: {createAt: {type: Date,default: Date.now()},updateAt: {type: Date,default: Date.now()}}
});UserSchema.pre('save', function (next) {if (this.isNew) {this.meta.updateAt = this.meta.createAt = Date.now();} else {this.meta.updateAt = Date.now();}next()
});UserSchema.statics = {fetch: function (cb) {return this.find({}).sort('meta.createAt').exec(cb)},findById: function (id, cb) {return this.findOne({_id: id}).sort('meta.createAt').exec(cb);},findByUid: function (uid, cb) {return this.findOne({uid: uid}).sort('meta.createAt').exec(cb);}
};module.exports = UserSchema;
复制代码
将schema发布为Model
这里我们定义一个userModule.js文件。用于引用schema,发布为model,向外导出。
var mongoose = require('mongoose');
var UserSchema = require('./userSchema');var User = mongoose.model('User',UserSchema);module.exports = User;
复制代码
增删改查
在controller层引入这个model,就可以使用之前定义的静态方法了。这个model还拥有Model.create(),Model.find(),Model.update(),Model.remove()方法,进行基本的CURD操作。下面举个简单的例子,实现增删改查功能。
var _ = require('underscore');
var User = require('../models/user');module.exports = {// 通过实例化model,创建一个model实例add: function(req, res, next) {var _user = new User(req.body.user);//相当于调用了Model.create(req.body)_user.save(function (err, user) {if (err) {//doSomething...} else {//doSomething...}})},delete: function (req, res) {var id = req.query._id;User.remove({_id: id}, function (err) {if (err) {//doSomething...} else {//doSomething...}})},update: function (req, res) {var id = req.body.id;var userParams = req.body;User.findById(id, function (err, user) {if (err) {//doSomething...} else {_user = _.extend(user, userParams);_user.save(function (err, user) {if(err) {//doSomething...} else {//doSomething...}})}})},list: function (req, res) {User.fetch(function (err, users) {var resultUsers=_.map(users, function(user){if (err){//doSomething...} else {//doSomething...}})},
};
复制代码
结尾
本篇文章介绍了mongoose的基本概念和使用事例,下篇文章中,会继续探讨schema的几种方法,使用promise方式代替回调调用、population的使用等进阶用法。