I am trying to fetch a bunch of documents within a transaction and also update all of them in the same transaction (because they reference each other, this has to be atomic). I know that all reads have to happen before all writes, but still I get The referenced transaction has expired or is no longer valid
error in my console.
I see all the ids printed by console.log(Transaction id: ${transactionId})
but never a single output of console.log(Transaction ${transactionId} fetched and pushed to array)
.
What is wrong with my transaction?
try {
return admin.firestore().runTransaction(async t => {
const bundleRef = admin.firestore().doc(`bundles/${bundleId}`)
const bundle = await t.get(bundleRef)
const bundleData = bundle.data()
const transactions:FirebaseFirestore.DocumentSnapshot[] = []
await bundleData!.transactionIds.forEach(async (transactionId: string) => {
console.log(`Transaction id: ${transactionId}`)
const transactionRef = admin.firestore().doc(`transactions/${transactionId}`)
const transaction = await t.get(transactionRef)
transactions.push(transaction)
console.log(`Transaction ${transactionId} fetched and pushed to array`)
})
console.log(`All transactions fetched`)
transactions.forEach(async transaction => {
console.log(`Updating transaction ${transaction.id}`)
const transactionData = transaction.data()
transactionData!.timestamp = admin.firestore.FieldValue.serverTimestamp()
t.update(transaction.ref, transactionData!)
console.log(`Transaction ${transaction.id} updated`)
})
console.log(`Update bundle ${bundle.id}`)
bundleData!.timestamp = admin.firestore.FieldValue.serverTimestamp()
t.update(bundle.ref, bundleData!)
console.log(`Finished`)
})
} catch (err) {
return Promise.reject(new Error("Transaction failed."));
}