I want to update two fields in a document in a collection called recipes and i used the batch update to do it:
let recipeRef = db.collection('recipes').doc(`${recipeId}`);
let batch = db.batch();
batch.update(recipeRef, {ratingsCount : admin.firestore.FieldValue.increment(1)});
batch.update(recipeRef, {totalRating : admin.firestore.FieldValue.increment(snap.data().rating)})
return batch.commit();
And I have a trigger function on the recipes collection like this:
exports.RecipeUpdated = functions.firestore
.document('recipes/{recipeId}')
.onUpdate((change, context) =>
{
//code
});
My question is as there are two updates in the above batch, will this also trigger the onUpdate function twice Or since the batch writes completes atomically, trigger will be called only ones? I want the trigger to be called only one time.
As @DougStevenson mentioned in his comment, you should just simply run the code and see the behaviour. But note, even if you are using the same recipeRef, you are creating two difference updates in your batch. In this case, the result that you'll get will be that onUpdate() will fire twice.
If you want to be called only once, then you should not create two different updates, you can create a single one. update() function allows you to pass multiple properties that can be updated. If you are using objects, than simply get a reference to the document, get it, make the changes and write it back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With