1. 扩展mongoose模型 #

业务分层

service(多个模型)->dao单个模型->model 模型定义

service(多个模型)->dao单个模型->model (模型定义+扩展方法)

2. statics 对类进行扩展 #

根据用户名查找用户文档

 //this指向model
PersonSchema.statics.findByUsername = function (username, callback) {
    return this.findOne({ username }, callback);
}
Person.findByUsername('zfpx', function (err, doc) {
    console.log(doc);
});

3. methods 对实例进行扩展 #

PersonSchema.methods.exist = function (callback) {
    let query = { username: this.username, password: this.password };
    return this.model('Person').findOne(query, callback);
}
let person = new Person({ username: 'zfpx', password: '123456', phone: '010-6255889', firstname: 'first', lastname: 'last' });
person.exist(function (err, doc) {
    console.log(err, doc);
});

4. virutal虚拟属性 #

PersonSchema.virtual('area').get(function () {
    //this指向实例
    return this.phone.split('-')[0];
});
PersonSchema.virtual('number').get(function () {
    return this.phone.split('-')[1];
});
let Person = conn.model('Person', PersonSchema);
let person = new Person({ username: 'zfpx', password: '123456', phone: '010-6255889', firstname: 'first', lastname: 'last' });
console.log(person.fullname, person.area, person.number);

5. hook #

在用户注册保存的时候,需要先把密码通过salt生成hash密码,并再次赋给password

PersonSchema.pre('save', function (next) {
    this.password = crypto.createHmac('sha256', 'zfpx').update(this.password).digest('hex');
    next();
});

PersonSchema.statics.login = function (username, password, callback) {
    password = crypto.createHmac('sha256', 'zfpx').update(password).digest('hex');
    return this.findOne({ username, password }, callback);
}

Person.login('zfpx', '123456', function (err, doc) {
    console.log(err, doc);
});

6. schema 插件 #

Schemas是可插拔的,也就是说,它们提供在应用预先打包能力来扩展他们的功能。

module.exports = exports = function lastModified(schema,options){
  schema.add({lastModify:Date});
  schema.pre('save',function(next){
    this.lastModify = new Date;
    next();
  });
  if(options&& options.index){
    schema.path('lastModify').index(options.index);
  }
}
let plugin = require('./plugin');
let Person = new Schema({});
Person.plugin(plugin,{index:true});
schema.add({age:Number});

7.MongoDB 聚合 #

MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。有点类似sql语句中的 count(*)。 aggregate() 方法 MongoDB中聚合的方法使用aggregate()。

7.1 语法 #

aggregate() 方法的基本语法格式如下所示:

>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

7.2 分组 #

现在我们通过以上集合计算每个作者所写的文章数,使用aggregate()计算结果如下:

> db.article.insert({uid:1,content:'1'});
> db.article.insert({uid:2,content:'2'});
> db.article.insert({uid:1,content:'3'});
 db.article.aggregate([{$group:{_id:'$uid',total:{$sum:1}}}]);
 { "_id" : 2, "total" : 1 }
{ "_id" : 1, "total" : 2 }
`

select uid, count(*) total from article group by uid

7.3 聚合的表达式 #

表达式 描述 实例
$sum 计算总和。 db.mycol.aggregate([{$group : {_id : "$uid", num_tutorial : {$sum : "$visit"}}}])
$avg 计算平均值 db.mycol.aggregate([{$group : {_id : "$uid", num_tutorial : {$avg : "$visit"}}}])
$min 获取集合中所有文档对应值得最小值。 db.mycol.aggregate([{$group : {_id : "$uid", num_tutorial : {$min : "$visit"}}}])
$max 获取集合中所有文档对应值得最大值。 db.mycol.aggregate([{$group : {_id : "$uid", num_tutorial : {$max : "$visit"}}}])
$push 在结果文档中插入值到一个数组中。 db.mycol.aggregate([{$group : {_id : "$uid", url : {$push: "$url"}}}])
$addToSet 在结果文档中插入值到一个数组中,但不创建副本。 db.mycol.aggregate([{$group : {_id : "$uid", url : {$addToSet : "$url"}}}])
$first 根据资源文档的排序获取第一个文档数据。 db.mycol.aggregate([{$group : {_id : "$uid", first_url : {$first : "$url"}}}])
$last 根据资源文档的排序获取最后一个文档数据 db.mycol.aggregate([{$group : {_id : "$uid", last_url : {$last : "$url"}}}])
db.article.insert({uid:1,content:'3',url:'url1'});
db.article.aggregate([{$group : {_id : "$uid", url : {$push: "$url"}}}])

7.4 管道的概念 #

管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数。 MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。

7.4.1 过滤显示字段 #

db.article.aggregate(
    { $project : {
        _id:0,
        content : 1 ,
    }}
 );

7.4.2 过滤文档 #

db.article.aggregate( [
                        { $match : { visit : { $gt : 10, $lte : 200 } } },
                        { $group: { _id: '$uid', count: { $sum: 1 } } }
 ] );

7.4.3 跳过指定数量 #

db.article.aggregate( [
                        { $match : { visit : { $gt : 10, $lte : 200 } } },
                        { $group: { _id: '$uid', count: { $sum: 1 } } },
                        { $skip : 1 }
 ] );

7.4.4 Mongoose中使用 #

Article.aggregate([
                        { $match : { visit : { $gt : 10, $lte : 200 } } },
                        { $group: { _id: '$uid', count: { $sum: 1 } } },
                        { $skip : 1 }
 ])
                .