My Firestore database is setup as follow:
/users/{userId}/tenants/{tenantId}/invoices/{invoiceId}
In each invoice document (InvoiceId), there are [“status”] and [“amount”] fields. ["status"] can be either “Pending” or “Paid”.
Every time there is an update to “status” inside of an invoiceId document, I would like to get the sum of all “amounts” where "status" == “Pending” from the respective invoice collection that was just updated. Then I want to set this new balance data to the respective tenantId document.
The following script calculates the sum for all documents where "status" == "Pending" whenever an invoiceId document is updated. However, I would like to calculate the sum of "amounts" only for the invoice collection that was updated (not all).
For example: suppose there's tenants A and B, each with many invoices. An invoice under tenant A is updated. I would like to calculate the new sum of "amounts" for tenant A (and not B).
Let me know if this is even possible.
exports.invoiceUpdated = functions.firestore
.document('/users/{userId}/tenants/{tenantId}/invoices/{invoiceId}')
.onUpdate(async (snap, context) => {
const task = await (db.collectionGroup('invoices').where('status', '==', "Pending").get());
if (task.empty) {
console.log('No pending invoices...')
return;
}
var total= 0;
task.forEach(element => {
console.log(element.data().amount)
total += element.data().amount
})
});```