Node mongoose 中间件 Middleware

1,169 阅读2分钟

主要内容讲解几个字面不易理解的 mongoose 中间的使用, 在看完这篇文章以及试验以下代码后,再去看相关文档会非常容易阅读。

  • 中间件分为前置 pre 和后置 post 两种, 也就是某种操作之前调用和之后调用。
'use strict'

const mongoose = require('mongoose');
mongoose.Promise = global.Promise
const db = mongoose.connect('mongodb://localhost:27017/mini');
const Schema = mongoose.Schema;

const student = {
    name: String,
    age: Number
};


const schema = new Schema(student)

//--------pre 前置
schema.pre('init', function (next) {
    console.log('init');
    next();
});
schema.pre('validate', function (next) {
    console.log('validate');
    next();
});
schema.pre('save', function (next) {
    console.log('save');
    next();
});

schema.pre('find', function(next) {
    console.log('find');
    next();
});
//--------post 后置
schema.post('init', function (doc,next) {
    console.log('post-init');
    next();
});
schema.post('validate', function (doc,next) {
    console.log('post-validate');
    next();
});
schema.post('save', function (doc,next) {
    console.log('post-save');
    next();
});
schema.post('find', function (doc,next) {
    console.log('post-find');
    next();
});


mongoose.model('student', schema);
const Model = mongoose.model('student');

在上面代码下添加

const model = new Model({
    'name': 'xiaohong',
    'age': 12
})

model.save()
    .then(function (doc) {
        console.log(doc._id);
    })
    .catch(function (err) {
        console.log(err);
    })
  • 运行后打印如下: validate post-validate save post-save 58f0ae9e9785fd1117289796 由上面看出,最先走的验证中间件 validate 而后是 post-validate 。然后才走的 save 保存, 而后post-save

  • 为了后面测试,上面的代码再运行一遍,让数据库有两条数据。

  • 注释上面添加的代码,添加以下代码

Model.find()
      .then(function (docs) {
        docs.forEach(function(doc) {
            console.log(doc._id);
        }, this);
    })
    .catch(function (err) {
        console.log(err);
    })

  • 运行后打印如下: find init post-init init post-init post-find 58f0ae9e9785fd1117289796 58f0b02915d61f11644a530c 由上面看出,find 只走了一次,但是 init 初始化数据走了两次,因为有两条数据所以就走了两次。

查询中间件:

count find findOne findOneAndRemove findOneAndUpdate insertMany update


还有并发执行中间件,更深入请到:http://mongoosejs.com/docs/middleware.html

个人博客: http://www.liangtongzhuo.com