# 扩展 mongoose 模型
# 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)
})
2
3
4
5
6
7
# 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)
})
2
3
4
5
6
7
8
9
10
11
12
13
14
# 4. virutal 虚拟属性
- virtual 是虚拟属性的意思,即原来 Schema 定义里是不存在该属性,后来通过 virutal 方法赋予的属性。
- Schema 中定义的属性是要保存到数据库里的,而 virtual 属性基于已有属性做的二次定义。
- 模型属性 = Schema 定义的属性+virtual 属性
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)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 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)
})
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 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)
}
}
2
3
4
5
6
7
8
9
10
let plugin = require("./plugin")
let Person = new Schema({})
Person.plugin(plugin, { index: true })
2
3
- Person 是用户自己定义的 Schema
- Person.plugin 是为 Person 增加 plugin
- plugin 有 2 个参数
- 插件对象 plugin
- 配置项 {index:true}
schema.add({ age: Number })
# 7.MongoDB 聚合
- MongoDB 中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。有点类似 sql 语句中的 count(*)。
- MongoDB 中聚合的方法使用 aggregate()。
# 7.1 语法
aggregate() 方法的基本语法格式如下所示:
db.getCollection("test").aggregate(AGGREGATE_OPERATION)
# 7.2 分组
现在我们通过以上集合计算每个作者所写的文章数,使用 aggregate()计算结果如下:
> db.article.insert({uid:1,content:'1',visit:1});
> db.article.insert({uid:2,content:'2',visit:2});
> db.article.insert({uid:1,content:'3',visit:3});
2
3
db.article.aggregate([{$group:{_id:'$uid',total:{$sum:1}}}]);
{ "_id" : 2, "total" : 1 }
{ "_id" : 1, "total" : 2 }
2
3
` select uid, count(*) total from article group by uid
# 7.3 聚合的表达式
表达式 | 描述 | 实例 |
---|---|---|
$sum | 计算总和。 | db.article.aggregate([{$group : {_id : "$uid", num_tutorial : {$sum : "$visit"}}}]) |
$avg | 计算平均值 | db.article.aggregate([{$group : {_id : "$uid", num_tutorial : {$avg : "$visit"}}}]) |
$min | 获取集合中所有文档对应值得最小值。 | db.article.aggregate([{$group : {_id : "$uid", num_tutorial : {$min : "$visit"}}}]) |
$max | 获取集合中所有文档对应值得最大值。 | db.article.aggregate([{$group : {_id : "$uid", num_tutorial : {$max : "$visit"}}}]) |
$push | 把某列的所有值都放到一个数组中 | db.article.aggregate([{$group : {_id : "$uid", url : {$push: "$url"}}}]) |
$addToSet | 返回一组文档中所有文档所选字段的全部唯一值的数组 | db.article.aggregate([{$group : {_id : "$uid", url : {$addToSet : "$url"}}}]) |
$first | 根据资源文档的排序获取第一个文档数据,可能为 null | db.article.aggregate([{$group : {_id : "$uid", first_url : {$first : "$url"}}}]) |
$last | 根据资源文档的排序获取最后一个文档数据,可能为 null | db.article.aggregate([{$group : {_id : "$uid", last_url : {$last : "$url"}}}]) |
db.article.insert({uid:1,content:'3',url:'url1'});
db.article.insert({uid:1,content:'4',url:'url1'});
db.article.insert({uid:1,content:'5',url:'url2'});
2
3
把某列的所有值都放到一个数组中
db.article.aggregate([{$group : {_id : "$uid", url : {$push: "$url"}}}])
{ "_id" : 1, "url" : [ "url1", "url1", "url2"] }
2
# 7.4 管道的概念
管道在 Unix 和 Linux 中一般用于将当前命令的输出结果作为下一个命令的参数。 MongoDB 的聚合管道将 MongoDB 文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。
- $project:修改输入文档的结构。可以用来重命名、增加或删除字段,也可以用于创建计算结果以及嵌套文档。
- $match:用于过滤数据,只输出符合条件的文档。$match 使用 MongoDB 的标准查询操作
- $limit:用来限制 MongoDB 聚合管道返回的文档数。
- $skip:在聚合管道中跳过指定数量的文档,并返回余下的文档。
- $unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
- $group:将集合中的文档分组,可用于统计结果。
- $sort:将输入文档排序后输出。
# 7.4.1 过滤显示字段
修改输入文档的结构。可以用来重命名、增加或删除字段,也可以用于创建计算结果以及嵌套文档
db.article.aggregate(
{ $project : {
_id:0,
content : 1 ,
}}
);
2
3
4
5
6
# 7.4.2 过滤文档
用于过滤数据,只输出符合条件的文档。$match 使用 MongoDB 的标准查询操作
db.article.aggregate( [
{ $match : { visit : { $gt : 10, $lte : 200 } } },
{ $group: { _id: '$uid', count: { $sum: 1 } } }
]);
2
3
4
# 7.4.3 跳过指定数量
在聚合管道中跳过指定数量的文档,并返回余下的文档。 `js var db = connect('school'); var vistors = []; for(var i=1;i<=20;i++){ vistors.push({uid:i,visit:i}); } print(vistors.length); db.vistors.insert(vistors);
db.vistors.aggregate( [ { $match : { visit : { $gt : 10, $lte : 200 } } }, { $group: { _id: '$uid', count: { $sum: 1 } } }, { $skip : 1 } ] );
# 7.4.5 $unwind
- 将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
- 使用$unwind 可以将 weekday 中的每个数据都被分解成一个文档,并且除了 weekday 的值不同外,其他的值都是相同的
db.vistors.aggregate([
{ $project: { _id: 1, uid: 1, type: 1, visit: 1 } },
{ $match: { visit: { $gte: 1, $lte: 10 } } },
{ $unwind: "$type" },
])
2
3
4
5
# 7.4.6 $group
将集合中的文档分组,可用于统计结果。
db.vistors.aggregate([
{ $project: { _id: 1, uid: 1, type: 1, visit: 1 } },
{ $match: { visit: { $gte: 1, $lte: 10 } } },
{ $unwind: "$type" },
{ $group: { _id: "$uid", count: { $sum: 1 } } },
{ $sort: { _id: 1 } },
{ $skip: 5 },
{ $limit: 5 },
])
2
3
4
5
6
7
8
9
# 7.4.5 Mongoose 中使用
Article.aggregate([
{ $match: { visit: { $gt: 10, $lte: 200 } } },
{ $group: { _id: "$uid", count: { $sum: 1 } } },
{ $skip: 1 },
])
2
3
4
5
.
MongoDemo