• 前后钩子即 pre()post() 方法(中间件

    • 中间件在 **schema** 上指定,类似静态方法或实例方法等

    • 可以在执行以下操作时设置前后钩子:

      init
      validate
      save
      remove
      count
      find
      findOne
      findOneAndRemove
      findOneAndUpdate
      insertMany
      update

    • 【pre()】:在执行某些操作前执行

    • 【post】:在执行某些操作前后执行,不可以使用next()

    案例:

    1. const mongoose = require('mongoose')
    2. mongoose.connect('mongodb://localhost:27017/student')
    3. var Schema =new mongoose.Schema({ name:String,grades:Number,test:{type:Number,default:0}})
    4. Schema.pre('find',function(next){
    5. console.log('我是pre方法1');
    6. next();
    7. });
    8. Schema.pre('find',function(next){
    9. console.log('我是pre方法2');
    10. next();
    11. });
    12. Schema.post('find',function(docs){
    13. console.log('我是post方法1');
    14. });
    15. Schema.post('find',function(docs){
    16. console.log('我是post方法2');
    17. });
    18. var stuModel = mongoose.model('grades', Schema);
    19. stuModel.find(function(err,docs){
    20. console.log(docs[0]);
    21. })
    22. /*
    23. 我是pre方法1
    24. 我是pre方法2
    25. 我是post方法1
    26. 我是post方法2
    27. {test: 34, _id: 6017befb5c36d64d08b72576,name: '小明',grades: 78,__v: 0}
    28. */