Reputation: 2284
I have firestore database and I would like to trigger a cloud functions when there is a change in a field of a firestore document. I would like the cloud function to look at what has changed and use the new data to update another filed of the firestore document.
Example
Lets assume the document in the picture has changed and has the new values as in the picture below
Now I would like to update the value of accuracy
to successes / attempts
, ie I would like accuracy to be 6/11 = 0.54
What should I write in the function? Here is what I have so far
exports.calculateAccuracy = functions.firestore.document('/users/{userId}/wordScores')
.onUpdate((change, context) => {
//what to write here?
});
Extra question: how many reads/writes I am going to consume to update the accuracy?
Thanks!!!
Upvotes: 2
Views: 2341
Reputation: 83191
The following should do the trick. Notice the path in the Cloud Firestore trigger (users/{userId}/wordScores/{scoreDocId}
): it points to a Document, not to a Collection. More info in the documentation.
exports.calculateAccuracy = functions.firestore
.document('users/{userId}/wordScores/{scoreDocId}')
.onUpdate((change, context) => {
const newValue = change.after.data();
const previousValue = change.before.data();
if ((newValue.attempts !== previousValue.attempts) || (newValue.successes !== previousValue.successes)) {
return change.after.ref.update({
accuracy: newValue.successes / newValue.attempts
});
} else {
return null;
}
});
Upvotes: 3