I am working on a Firebase cloud function to update a field value for every element of the array I provide.
Below is my loop.
I would like for it to add a document to another collection as soon as this loop has been completed.
// FOR EACH ITEM
sortedArray.forEach(([key, val]) => {
walletRef.doc('j10wmCUhUWPxYJpIElBxmFAEI6l1').update({
[val.product]: admin.firestore.FieldValue.increment(val.quantity),
})
})
When I try to add a .then like below, it fails
// FOR EACH ITEM
sortedArray.forEach(([key, val]) => {
walletRef.doc('document_id_here').update({
[val.product]: admin.firestore.FieldValue.increment(val.quantity),
})
}).then((doc) => {
logsRef.add({
user_id: "document_id_here",
product: items,
transactionType: "purchase",
date: new Date(),
})
});
Logged error:
textPayload: "Function execution took 2594 ms, finished with status: 'crash'"
The field values are updated but the new document is not created.
Please help.
Thanks.
>Solution :
Your update loop seems unnecessary since you’re performing the operations on the same document.
Try something like this instead, setting multiple properties at once
walletRef
.doc("document_id_here")
.update(
Object.fromEntries(
sortedArray.map(({ product, quantity }) => [
product,
admin.firestore.FieldValue.increment(quantity),
])
)
)
.then((writeResult) => {
// ...
});
From the docs for Increment a numeric value…
★ Note: If the field does not exist or if the current field value is not a numeric value, the operation sets the field to the given value