【mongo】mongoose

mongoose

api:hhttp://mongoosejs.com/docs/ap...html

安装及引用

安装

npm install mongoosejava

引用mongoose

var mongoose = require(“mongoose”);正则表达式

使用mongoose连接数据库

api

mongoose.connect('mongodb://username:password@host:port/database?options...');mongodb

test

mongoose.connect('mongodb://localhost/myapp');数据库

示例

var mongoose = require(“mongoose”); 
var db = mongoose.connect(“mongodb://127.0.0.1:27017/test”); 
db.connection.on(“error”, function (error) { 
console.log(“数据库链接失败:” + error); 
}); 
db.connection.on(“open”, function () { 
console.log(“——数据库链接成功!——”); 
});

MongoDB基础

Schema : 一种以文件形式存储的数据库模型骨架,不具有数据库的操做能力npm

Model : 由Schema发布生成的模型,具备抽象属性和行为的数据库操做对api

Entity : 由Model建立的实体,他的操做也会影响数据库数组

Schema

一种以文件形式存储的数据库模型骨架,没法直接通往数据库端,也就是说它不具有对数据库的操做能力.能够说是数据属性模型(传统意义的表结构),又或着是“集合”的模型骨架promise

/* 定义一个 Schema */
var mongoose = require("mongoose");

var TestSchema = new mongoose.Schema({
    name : { type:String },//属性name,类型为String
    age  : { type:Number, default:0 },//属性age,类型为Number,默认为0
    time : { type:Date, default:Date.now },
    email: { type:String,default:''}
});

上面这个 TestSchema包含4个属性 [name, age, time, email]app

基本属性类型有:字符串、日期型、数值型、布尔型(Boolean)、null、数组、内嵌文档等

api

Schema.prototype.clone()

var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://127.0.0.1:27017/test'); 
var mongooseSchema = new mongoose.Schema({
  username : {type : String, default : '匿名用户'},
  title    : {type : String},
  content  : {type : String},
  time     : {type : Date, default: Date.now},
  age      : {type : Number}
});
var cloneSchema = mongooseSchema.clone();

Schema.prototype.add()

var ToySchema = new mongoose.Schema;
ToySchema.add({ name: 'string', color: 'string', price: 'number' });

Schema.prototype.path()

schema.path('name') // returns a SchemaType
schema.path('name', Number) // changes the schemaType of `name` to Number
var mongooseSchema = new mongoose.Schema({
  username : {type : String, default : '匿名用户'},
  title    : {type : String},
  content  : {type : String},
  time     : {type : Date, default: Date.now},
  age      : {type : Number}
});
console.log(mongooseSchema.path('time'));
输出:
SchemaDate {
  path: 'time',
  instance: 'Date',
  validators: [],
  setters: [],
  getters: [],
  options: { type: [Function: Date], default: [Function: now] },
  _index: null,
  defaultValue: [Function: now] }

中间件api

参考文档:https://www.cnblogs.com/surah...

Schema.prototype.pre()

有2种类型的pre hook,串行(seria)和并行(parallel)。

Serial

串行中间件是一个接一个执行,每一个中间件调用next。

var schema = new Schema(..);
schema.pre('save', function(next) {
  // 作些什么
  next();
});
Parallel

并行中间件提供更细粒度的操做

var schema = new Schema(..);

// 'true'表示这是一个并行中间件. 若是你想要使用并行中间件,你必须指定true做为第二个参数 
schema.pre('save', true, function(next, done) {
  // 下一个要执行的中间件并行执行
  next();
  setTimeout(done, 100);
});

Schema.prototype.post()

Post 中间件

post中间件在hooked方法和全部它的pre中间件完成后才执行。post中间件不直接接收流控制,如没有next和done回调都传递给它。post hook可以为这些方法注册传统的事件监听器。

schema.post('init', function(doc) {
  console.log('%s has been initialized from the db', doc._id);
});
schema.post('validate', function(doc) {
  console.log('%s has been validated (but not saved yet)', doc._id);
});
schema.post('save', function(doc) {
  console.log('%s has been saved', doc._id);
});
schema.post('remove', function(doc) {
  console.log('%s has been removed', doc._id);
});

Schema.prototype.method()

追加方法
Schema.methods.say = function(){console.log(‘hello’);};
//静态方法,只限于在Model层就能使用

实例

var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://127.0.0.1:27017/test'); 
var mongooseSchema = new mongoose.Schema({
  username : {type : String, default : '匿名用户'},
  title    : {type : String},
  content  : {type : String},
  time     : {type : Date, default: Date.now},
  age      : {type : Number}
});
// 添加 mongoose 实例方法
mongooseSchema.methods.findbyusername = function(username, callback) {
  return this.model('mongoose').find({username: username}, callback);
}
var mongooseModel = db.model('mongoose', mongooseSchema);
var mongooseEntity = new mongooseModel();
mongooseEntity.findbyusername('model_demo_username', function(error, result){
          if(error) {
              console.log(error);
          } else {
              console.log(result);
          }
          //关闭数据库连接
          db.close();
      });
公共方法

这样Model和Entity的实例就能使用这个方法了

mongooseSchema.method('meow', function () {
  console.log('meeeeeoooooooooooow');
})

var Kitty = db.model('Kitty', mongooseSchema);

var fizz = new Kitty;
fizz.meow();
schema.method({
    purr: function () {}
  , scratch: function () {}
});

// later
fizz.purr();
fizz.scratch();

Schema.prototype.static()

静态方法,只限于在Model层就能使用

var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://127.0.0.1:27017/test'); 
var mongooseSchema = new mongoose.Schema({
  username : {type : String, default : '匿名用户'},
  title    : {type : String},
  content  : {type : String},
  time     : {type : Date, default: Date.now},
  age      : {type : Number}
});
// 添加 mongoose 静态方法,静态方法在Model层就能使用
mongooseSchema.statics.findbytitle = function(title, callback) {
  return this.model('mongoose').find({title: title}, callback);
}
var mongooseModel = db.model('mongoose', mongooseSchema);

mongooseModel.findbytitle('emtity_demo_title',function(err,res){})

model

参考文档:http://www.cnblogs.com/surahe...
由Schema构造生成的模型,除了Schema定义的数据库骨架之外,还具备数据库操做的行为,相似于管理数据库属性、行为的类

var db = mongoose.connect("mongodb://127.0.0.1:27017/test");

// 建立Model
var TestModel = db.model("test1", TestSchema);
test1 数据库中的集合名称, 不存在会建立.

建立Model

db.model(“test1”, TestSchema );

1.构造函数, 参数1:集合名称, 参数2:Schema实例

var Kitty = db.model('Kitty', mongooseSchema);

查询

model.find({}, callback);
参数1忽略,或为空对象则返回全部集合文档

mongooseSchema.statics.findbytitle = function(title, callback) {
  return this.model('mongoose').find({title: title}, callback);
}
// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});
// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});
var ff = mongooseModel.find({ username: 'model_demo_username'},function(e,r){
        console.log('ff',r)
      });
// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});

// executes immediately, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

model.find({},field,callback);

过滤查询,参数2: {‘name’:1, ‘age’:0} 查询文档的返回结果包含name , 不包含age.(_id默认是1)

// name LIKE john and only selecting the "name" and "friends" fields, executing immediately
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })

model.find({},null,{limit:20});

过滤查询,参数3: 游标操做 limit限制返回结果数量为20个,如不足20个则返回全部.

// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })

// passing options and executing immediately
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});

model.findOne({}, callback);

查询找到的第一个文档

// find one iphone adventures - iphone adventures??
Adventure.findOne({ type: 'iphone' }, function (err, adventure) {});

// same as above
Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {});

// select only the adventures name
Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {});

// same as above
Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {});

// specify options, in this case lean
Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback);

// same as above
Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback);

// chaining findOne queries (same as above)
Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback);

model.findById(‘obj._id’, callback);
查询找到的第一个文档,同上. 可是只接受 __id 的值查询

// find adventure by id and execute immediately
Adventure.findById(id, function (err, adventure) {});

// same as above
Adventure.findById(id).exec(callback);

// select only the adventures name and length
Adventure.findById(id, 'name length', function (err, adventure) {});

// same as above
Adventure.findById(id, 'name length').exec(callback);

// include all properties except for `length`
Adventure.findById(id, '-length').exec(function (err, adventure) {});

// passing options (in this case return the raw js objects, not mongoose documents by passing `lean`
Adventure.findById(id, 'name', { lean: true }, function (err, doc) {});

// same as above
Adventure.findById(id, 'name').lean().exec(function (err, doc) {});

建立

Model.create(文档数据, callback))
在集合中建立一个文档

// 增长记录 基于model操做
var doc = {username : 'model_demo_username', title : 'model_demo_title', content : 'model_demo_content'};
mongooseModel.create(doc, function(error){
    if(error) {
        console.log(error);
    } else {
        console.log('save ok');
    }
    // 关闭数据库连接
    db.close();
});

更新

Model.update(conditions, update, function(error)
参数1:查询条件, 参数2:更新对象,可使用MondoDB的更新修改器

//修改记录
//mongooseModel.update(conditions, update, options, callback);
var conditions = {username : 'model_demo_username'};
var update     = {$set : {age : 27, title : 'model_demo_title_update'}};
var options    = {upsert : true};
mongooseModel.update(conditions, update, options, function(error){
   if(error) {
       console.log(error);
   } else {
       console.log('update ok!');
   }
   //关闭数据库连接
   db.close();
});

删除

Model.remove(conditions,callback);
参数1:查询条件

// 删除记录
var conditions = {username: 'emtity_demo_username'};
mongooseModel.remove(conditions, function(error){
    if(error) {
        console.log(error);
    } else {
        console.log('delete ok!');
    }

    //关闭数据库连接
    db.close();
});

Model.where()

User.find({age: {$gte: 21, $lte: 65}}, callback);
等于:
User.where('age').gte(21).lte(65).exec(callback);

Entity

1.构造函数, 其实就是model的实例

new TestModel( { name:‘xueyou’, age:21 } );

2.建立, 在集合中建立一个文档.

Entity.save(callback);

由Model建立的实体,使用save方法保存数据,Model和Entity都有能影响数据库的操做,但Model比Entity更具操做性

var TestEntity = new TestModel({
       name : "Lenka",
       age  : 36,
       email: "lenka@qq.com"
});
console.log(TestEntity.name); // Lenka
console.log(TestEntity.age); // 36
var mongooseModel = db.model('mongoose', mongooseSchema);
var doc = {username : 'model_demo_username', title : 'emtity_demo_title', content : 'emtity_demo_content'};
var mongooseEntity = new mongooseModel(doc);
mongooseEntity.save(function(error) {
    if(error) {
        console.log(error);
    } else {
        console.log('saved OK!');
    })

修改器和更新器

更新修改器:

‘$inc’ 增减修改器,只对数字有效.下面的实例: 找到 age=22的文档,修改文档的age值自增1

Model.update({‘age’:22}, {’$inc’:{‘age’:1} }  );
执行后: age=23

‘$set’ 指定一个键的值,这个键不存在就建立它.能够是任何MondoDB支持的类型.

Model.update({‘age’:22}, {’$set’:{‘age’:‘haha’} }  );
执行后: age=‘haha’

‘$unset’ 同上取反,删除一个键

Model.update({‘age’:22}, {’$unset’:{‘age’:‘haha’} }  );
执行后: age键不存在

数组修改器:

‘$push’ 给一个键push一个数组成员,键不存在会建立

Model.update({‘age’:22}, {’$push’:{‘array’:10} }  );
执行后: 增长一个 array 键,类型为数组, 有一个成员 10

‘$addToSet’ 向数组中添加一个元素,若是存在就不添加

Model.update({‘age’:22}, {’$addToSet’:{‘array’:10} }  );
执行后: array中有10因此不会添加

‘$each’ 遍历数组, 和 $push 修改器配合能够插入多个值

Model.update({‘age’:22}, {’$push’:{‘array’:{’$each’: [1,2,3,4,5]}} } );
执行后: array : [10,1,2,3,4,5]

‘$pop’ 向数组中尾部删除一个元素

Model.update({‘age’:22}, {’$pop’:{‘array’:1} }  );
执行后: array : [10,1,2,3,4]  tips: 将1改为-1能够删除数组首部元素

‘$pull’ 向数组中删除指定元素

Model.update({‘age’:22}, {’$pull’:{‘array’:10} }  );
执行后: array : [1,2,3,4]  匹配到array中的10后将其删除

条件查询

“$lt” 小于
“$lte” 小于等于
“$gt” 大于
“$gte” 大于等于
“$ne” 不等于

Model.find({“age”:{ “$get”:18 , “$lte”:30 } } );
查询 age 大于等于18并小于等于30的文档

或查询 OR

‘$in’ 一个键对应多个值
‘$nin’ 同上取反, 一个键不对应指定值
“$or” 多个条件匹配, 能够嵌套 $in 使用
“$not” 同上取反, 查询与特定模式不匹配的文档
Model.find({“age”:{ “$in”:[20,21,22.‘haha’]} } );
查询 age等于20或21或21或’haha’的文档

Model.find({"$or" :  [ {‘age’:18} , {‘name’:‘xueyou’} ] });
查询 age等于18 或 name等于’xueyou’ 的文档

类型查询

null 能匹配自身和不存在的值, 想要匹配键的值 为null, 就要经过 “$exists” 条件断定键值已经存在
"$exists" (表示是否存在的意思)

Model.find(“age” :  { “$in” : [null] , “exists” : true  } );
查询 age值为null的文档

Model.find({name: {$exists: true}},function(error,docs){
  //查询全部存在name属性的文档
});

Model.find({telephone: {$exists: false}},function(error,docs){
  //查询全部不存在telephone属性的文档
});

正则表达式

MongoDb 使用 Prel兼容的正则表达式库来匹配正则表达式

find( {“name” : /joe/i } )    
查询name为 joe 的文档, 并忽略大小写

 find( {“name” : /joe?/i } )
查询匹配各类大小写组合

查询数组

Model.find({“array”:10} );
查询 array(数组类型)键中有10的文档, array : [1,2,3,4,5,10] 会匹配到

Model.find({“array[5]”:10} );
查询 array(数组类型)键中下标5对应的值是10, array : [1,2,3,4,5,10] 会匹配到

‘$all’ 匹配数组中多个元素

Model.find({“array”:[5,10]} );
查询 匹配array数组中 既有5又有10的文档

‘$size’ 匹配数组长度

Model.find({“array”:{"$size" : 3} } );
查询 匹配array数组长度为3 的文档

‘$slice’ 查询子集合返回

Model.find({“array”:{"$skice" : 10} } );
查询 匹配array数组的前10个元素
Model.find({“array”:{"$skice" : [5,10] } } );
查询 匹配array数组的第5个到第10个元素

where

用它能够执行任意javacript语句做为查询的一部分,若是回调函数返回 true 文档就做为结果的一部分返回

find( {"$where" : function(){
        for( var x in this ){
         //这个函数中的 this 就是文档
        }
        
        if(this.x !== null && this.y !== null){
            return this.x + this.y === 10 ? true : false;
        }else{
            return true;
        }
        
        
}  }  )

简化版本

find( {"$where" :  "this.x + this.y === 10" } )
    find( {"$where" : " function(){ return this.x + this.y ===10; } " } )

游标

  1. limit(3) 限制返回结果的数量,
  2. skip(3) 跳过前3个文档,返回其他的
  3. sort( {“username”:1 , “age”:-1 } ) 排序 键对应文档的键名, 值表明排序方向, 1 升序, -1降序