# 中间件
- 中间件称前置(pre)和后置(post)钩子
- 在模式(Schema)级别指定,有 4 种类型的中间件:
- 文档(document)中间件包括 init/validate/save/remove,
- 模型(model)中间件包括 insertMany,
- 聚合(aggregate)中间件包括 aggregate 和查询(query )中间件包括 count/find/findOne/findOneAndRemove/findOneAndUpdate/remove/update/updateOne/updateMany。
在这些方法事件注册上“pre”方法或后置“post”方法,就是在执行该方法前会先执行 pre 方法,完后再执行 post 方法
/**
* MongoDB数据库操作:mongoose对象模型库之中间件pre和post钩子
*/
const mongoose = require("mongoose");
const { compileFunction } = require("vm");
//与数据库建立连接
mongoose.connect("mongodb://127.0.0.1:27017/studentdb",{useNewUrlParser: true, useUnifiedTopology: true});
const conn = mongoose.connection;
conn.on("error",(err)=>{
console.error("数据库连接失败:"+err);
});
conn.once("open",()=>{
console.log("数据库连接成功!");
});
//模式定义:主要指定对应的MongoDB集合的字段和字段类型。
let studentSchema = mongoose.Schema({
Id:{type:String,required:[true,"Id不能为空"]},//内置验证器
Name:String,
Age:{type:Number,min:[1,"年龄不能小于0"],max:100},
Weight:Number
});
//pre钩子注册:
studentSchema.pre("init",(doc)=>{
console.log("pre-init");
});
studentSchema.pre("validate",(next)=>{
console.log("validate");
next();
});
studentSchema.pre('save', function (next) {
console.log('save');
next();
});
studentSchema.pre('find', function(next) {
console.log('find');
next();
});
//post钩子注册:
studentSchema.post("init",(doc)=>{
console.log("post-init");
});
studentSchema.post("validate",(doc,next)=>{
console.log("post-validate");
next();
});
studentSchema.post('save', function (doc,next) {
console.log('post-save');
next();
});
studentSchema.post('find', function (doc,next) {
console.log('post-find');
next();
});
//模型创建:将模式编译成模型
let Student = mongoose.model("students",studentSchema);
//save方法引起的相关已注册的钩子的执行
let studentObj = new Student({"Id":1005,"Name":"WQ","Age":1,"Weight":34.5});
studentObj.save((err,doc)=>{
if(err) throw err;
console.log("1.使用实例save()方法保存成功!");
});
//find方法引起的相关已注册的钩子的执行
Student.find((err,students)=>{
if(err) throw err;
console.log("查询所有学生结果如下:");
console.log(students.toString());
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81