在保存后中间件中使用静态方法

Wen*_*McF 1 static-methods mongoose node.js

我有一个静态方法来执行 find() 并在应用程序启动时将营销活动数据添加到 Redis。

CampaignSchema.statics.activeCampaignsToRedis = function () {
    this
        .find()
        .where('active').equals(true)
  ...
};
Run Code Online (Sandbox Code Playgroud)

我想添加一个保存后挂钩,每当添加或修改新的营销活动时,该挂钩都会重新运行静态方法来更新 Redis 中的数据。

CampaignSchema.post('save', function (next) {
  // call CampaignSchema.statics.activeCampaignsToRedis();
});
Run Code Online (Sandbox Code Playgroud)

Joh*_*yHK 6

您的保存后中间件回调接收保存的文档作为其一个参数,而不是下一个函数。从那里您可以通过其(未记录的)属性访问文档的模型 constructor

因此,您可以将中间件函数编写为:

CampaignSchema.post('save', function (doc) {
  doc.constructor.activeCampaignsToRedis();
});
Run Code Online (Sandbox Code Playgroud)