[英]Hook in Mongoose works in PRE but doesn't work in POST
使用 Mongoose 挂钩,我需要如果名为 outstandingBalance 的属性的值为零,则状态会自动更改为 false。
尝试使用 Mongoose 的 PRE 挂钩来执行此操作但只能通过在 outstandingBalance 之前已经为零之后重新调用请求来实现。 这就是我决定使用 POST 挂钩的原因,这样一旦将 outstandingBalance 设置为零,它就会将属性从 statua 更改为 false。
这是我与 PRE 一起使用的代码,它工作正常但对于我需要的东西来说并不可行:
SaleSchema.pre('findOneAndUpdate', async function() {
const docToUpdate = await this.model.findOne(this.getQuery())
if (docToUpdate.outstandingBalance < 1) {
this._update.status = false;
}
})
所以我决定将 PRE 更改为 POST 但它永远不会起作用:
SaleSchema.post('findOneAndUpdate', async function() {
const docToUpdate = await this.model.findOne(this.getQuery())
if (docToUpdate.outstandingBalance < 1) {
this._update.status = false;
}
})
'POST'表示全部完成,之后没有任何动作(数据已经更新),设置状态后必须再次保存才能更新状态。
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;
}
})
这是能够使用 Pre hook 根据 outstandingBalance 值将状态设置为 false 的解决方案:
SaleSchema.pre('findOneAndUpdate', function (next) {
if(this._update.$set.outstandingBalance < 1) {
this._update.status = false
}
next();
});
非常感谢他的帮助,@hoangdv 指导我找到了解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.