【问题标题】:Is there a better way to listen to events on Mongoose models?有没有更好的方法来监听 Mongoose 模型上的事件?
【发布时间】:2020-12-23 04:27:43
【问题描述】:

创建连接时,此函数运行:

function setupModelListenersForConnection(c){
    var Job = c.model('Job');
    Job.addListener('created', function(jobInstance){
    });
    console.log('Models have been wired!');
}

在我的工作架构中:

JobSchema.post('save', function(next){
  this.db.models.Job.emit('created', this);
})

我不太喜欢this.db.models.Job,我认为有更好的方法;)非常感谢

为什么我需要它?

想象一下创建了一个工作。我想更新工作人员并将其设置为当前工作和新状态(忙碌)。

我喜欢解耦模型,这样 Job 模型就不必知道 Worker 模型。只知道一些关于工作人员的详细信息,例如 id 和 name。

【问题讨论】:

  • 我正在尝试做同样的事情。你有没有得到这个问题的答案?
  • 不多:/但如果您找到任何答案,请联系我

标签: mongoose events listener


【解决方案1】:

mongoose-lifecycle 就是这样做的

JobSchema.post('save', function(next){
  var model = this.model(this.constructor.modelName);
  model.emit('created', this);
})

【讨论】:

    猜你喜欢
    • 2013-11-20
    • 1970-01-01
    • 2011-07-28
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多