问题
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();
}
});
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?
回答1:
Found a way!
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();
});
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.
来源:https://stackoverflow.com/questions/48065200/how-do-you-update-a-document-in-keystonejs-on-save-click