Mongoose 中的 Hook 在 PRE 中有效,但在 POST 中无效
Hook in Mongoose works in PRE but doesn't work in POST
使用 Mongoose 挂钩,我需要如果 属性 调用的 outstandingBalance 的值为零,状态会自动更改为 false。
尝试使用 Mongoose 的 PRE 挂钩来执行此操作是可行的,但只能在 outstandingBalance 之前已经为零之后重新调用请求。这就是为什么我决定使用 POST 挂钩,这样一旦将 outstandingBalance 设置为零,它就会将 属性 从状态更改为 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
挂钩适合您的情况,只需更改条件:检查更新数据而不是当前数据
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 指导我找到了解决方案。
使用 Mongoose 挂钩,我需要如果 属性 调用的 outstandingBalance 的值为零,状态会自动更改为 false。
尝试使用 Mongoose 的 PRE 挂钩来执行此操作是可行的,但只能在 outstandingBalance 之前已经为零之后重新调用请求。这就是为什么我决定使用 POST 挂钩,这样一旦将 outstandingBalance 设置为零,它就会将 属性 从状态更改为 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
挂钩适合您的情况,只需更改条件:检查更新数据而不是当前数据
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 指导我找到了解决方案。