Mongoose schema.post 事件在版本 >= 4.8.0 中中断

Mongoose schema.post events broken in versions >= 4.8.0

在一个使用 mongoose 的节点应用程序中,我定义了一些 mongoose 中间件挂钩,如下所示:

mongoose.model('MyModel').schema.post('save', function(document) {
    // following is executed in 4.7.9 but not 4.8.0
    console.log('saved');
});

这些挂钩在 4.7.9 及之前的 mongoose 版本中运行良好,但如果我在我的应用程序中将 mongoose 更新为 4.8.0,那么在没有其他更改的情况下,这些挂钩根本无法被调用。没有警告或错误。

http://mongoosejs.com/docs/middleware.html 表明定义这些钩子的方式没有改变。我需要在 4.8.0+ 中做些不同的事情来保留这种行为吗?

我很确定您需要在创建模型之前声明中间件:

let MySchema = new mongoose.Schema(...);

MySchema.post('save', ...);

let MyModel = mongoose.model('MyModel', MySchema);

另请参阅:https://github.com/Automattic/mongoose/issues/4971#issuecomment-279238187