前后钩子即
pre()和post()方法(中间件)中间件在
**schema**上指定,类似静态方法或实例方法等可以在执行以下操作时设置前后钩子:
init
validate
save
remove
count
find
findOne
findOneAndRemove
findOneAndUpdate
insertMany
update
【pre()】:在执行某些操作前执行【post】:在执行某些操作前后执行,不可以使用next()
案例:
const mongoose = require('mongoose')mongoose.connect('mongodb://localhost:27017/student')var Schema =new mongoose.Schema({ name:String,grades:Number,test:{type:Number,default:0}})Schema.pre('find',function(next){console.log('我是pre方法1');next();});Schema.pre('find',function(next){console.log('我是pre方法2');next();});Schema.post('find',function(docs){console.log('我是post方法1');});Schema.post('find',function(docs){console.log('我是post方法2');});var stuModel = mongoose.model('grades', Schema);stuModel.find(function(err,docs){console.log(docs[0]);})/*我是pre方法1我是pre方法2我是post方法1我是post方法2{test: 34, _id: 6017befb5c36d64d08b72576,name: '小明',grades: 78,__v: 0}*/
