I am encountering an issue where I am attempting to retrieve multiple documents within a transaction and then update them all in the same transaction (due to their interdependence). Despite following the rule of ensuring all reads occur before any writes, I keep receiving the error message
The referenced transaction has expired or is no longer valid
in my console.
Although I can see the transaction ids being logged with
console.log(Transaction id: ${transactionId})
, I never see any output from console.log(Transaction ${transactionId} fetched and pushed to array)
.
What could be causing my transaction to fail?
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."));
}