简体   繁体   English

Mongoose 中的钩子在 PRE 中有效,但在 POST 中无效

[英]Hook in Mongoose works in PRE but doesn't work in POST

Using Mongoose hooks, I need that if the property called outstandingBalance has a value of zero, the status automatically changes to false.使用 Mongoose 挂钩,我需要如果名为 outstandingBalance 的属性的值为零,则状态会自动更改为 false。

Trying to do this using Mongoose's PRE hook works but only by re-invoking the request after outstandingBalance was already zero before.尝试使用 Mongoose 的 PRE 挂钩来执行此操作但只能通过在 outstandingBalance 之前已经为零之后重新调用请求来实现。 That is why I have decided to use the POST hook so that once the setting of outstandingBalance to zero is finished, it changes the property from statua to false.这就是我决定使用 POST 挂钩的原因,这样一旦将 outstandingBalance 设置为零,它就会将属性从 statua 更改为 false。

This is the code that I use with PRE that works fine but is not really viable for what I need:这是我与 PRE 一起使用的代码,它工作正常但对于我需要的东西来说并不可行:

SaleSchema.pre('findOneAndUpdate', async function() {
    const docToUpdate = await this.model.findOne(this.getQuery())
  
    if (docToUpdate.outstandingBalance < 1) {
      
      this._update.status = false;
    }
  })

So I decided to change PRE to POST but it never works:所以我决定将 PRE 更改为 POST 但它永远不会起作用:

SaleSchema.post('findOneAndUpdate', async function() {
    const docToUpdate = await this.model.findOne(this.getQuery())
  
    if (docToUpdate.outstandingBalance < 1) {
      
      this._update.status = false;
    }
  })

'POST' means all done, there is no action after that(the data is already updated), you have to save it again after setting the status to update the status. 'POST'表示全部完成,之后没有任何动作(数据已经更新),设置状态后必须再次保存才能更新状态。

PRE hook is correct for your case, just change the condition: Checking on update data instead of current data PRE hook 适合您的情况,只需更改条件:Checking on update data instead of current data

SaleSchema.pre('findOneAndUpdate', async function() {
    const docToUpdate = await this.model.findOne(this.getQuery())
  
    if (this._update.outstandingBalance < 1 || (!this._update.outstandingBalance && docToUpdate.outstandingBalance < 1)) {
      
      this._update.status = false;
    }
  })

This was the solution to be able to set the status to false depending on the outstandingBalance value using the Pre hook:这是能够使用 Pre hook 根据 outstandingBalance 值将状态设置为 false 的解决方案:

SaleSchema.pre('findOneAndUpdate', function (next) {

    if(this._update.$set.outstandingBalance < 1) {
        this._update.status = false
    }
    next();
});

Many thanks to him for his help as @hoangdv guided me to find the solution.非常感谢他的帮助,@hoangdv 指导我找到了解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM