如何在保存单击时更新KeystoneJS中的文档? [英] How do you update a document in KeystoneJS on save click?
问题描述
我想在更改另一个字段后更新文档中的特定字段. 我有一个产品代码,还有一些价格和标题等字段,这些字段是从外部api获取的.
I want to update specific fields in a document after changing another field. I've got a product code and a few fields like price and title which I get from an external api.
每当有人在后端更改产品代码时,我都希望更新文档中的价格和标题. 首先,我尝试在模式上使用猫鼬发布保存钩子.这导致无休止的循环,因为在保存文档后,它不断更新并因此保存了文档. 然后,我实现了一个布尔值,以确保后保存挂钩仅被调用一次,如下所示:
I want to update the price and title in the document whenever someone changes the product code in the backend. First I tried using a mongoose post save hook on the schema. This resulted in an endless loop, since it kept updating and thus saving the document, after saving the document. Then I implemented a boolean to make sure the post save hook is called only once, which looks something like this:
let postSaveTriggered = false;
//update our product!
Product.schema.post('save', function(doc, next) {
if (!postSaveTriggered) {
postSaveTriggered = true;
api.product.updateInfo(doc, function() { //this updates the document
next();
});
} else {
postSaveTriggered = false;
next();
}
});
但是我只希望此功能在用户实际更改产品代码时触发,而不是在一般情况下更新产品时触发.我也在执行一项计划任务,以更新产品的价格,显然,我不希望在这种情况下触发后保存挂钩. 有什么方法可以使用KeystoneJS后端实现我想要的功能?
But I only want this function to trigger when a user actually changes the product code, not when the product is updated in general. I'm also running a cron job to update the prices of the products and I obviously don't want the post save hook to trigger at all in this scenario. Is there any way to achieve what I want using the KeystoneJS backend?
推荐答案
找到了方法!
首先使用 pre 保存钩来监视产品代码中的更改:
First use a pre save hook to watch for changes in the product code:
let updateProduct = false;
Product.schema.pre('save', function(next) {
updateProduct = this.isModified('code');
next();
});
然后仅当updateProduct为true时,才在发布保存钩子中进行更新:
Then simply only update in the post save hook when updateProduct is true:
Product.schema.post('save', function(doc, next) {
if (updateProduct) {
updateProduct = false;
api.product.updateInfo(doc, function() {
next();
});
} else {
next();
}
});
为我工作,尽管看起来仍然不必要复杂.
Works for me, still seems unnecessary complicated though.
这篇关于如何在保存单击时更新KeystoneJS中的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!