I am quite new to Firebase and NoSQL databases and I am developing server-side.
My goal is to read two collections in one transaction (and lock the included documents for consistency). On the one hand I want to read up to 499 documents from collection A and on the other hand exactly one document from collection B, as illustrated in the following code example.
export const transactionTest = function(nextFunction: () => void) {
const collection_A_reference = admin.firestore().collection("A").limit(499);
const collection_B_doc_B1_reference = admin.firestore().collection("B").doc("B1");
try {
admin.firestore().runTransaction((t) => {
return t.get(collection_A_reference)
.then((coll_A_snapshot) => {
if (!(coll_A_snapshot.empty)) {
t.get(collection_B_doc_B1_reference)
.then((coll_B_doc_B1_snapshot) => {
if (coll_B_doc_B1_snapshot.exists) {
let counter = coll_B_doc_B1_snapshot.get("COUNTER");
for (let i = 0; i < coll_A_snapshot.docs.length; i++) {
counter++;
t.update(coll_A_snapshot.docs[i].ref, {COUNTER: counter});
}
t.update(coll_B_doc_B1_snapshot.ref, {COUNTER: counter});
} else {
console.log("coll_B_doc_B1_snapshot does not exist");
}
});
} else {
console.log("coll_A_snapshot is empty");
}
});
});
} catch (e) {
console.log("Transaction failure:", e);
nextFunction();
}
nextFunction();
};
However, it seems like a second t.get is not allowed and is throwing the following error:
(node:13460) UnhandledPromiseRejectionWarning: Error: 10 ABORTED: The referenced transaction has expired or is no longer valid
Does someone know how to implement this (especially syntactically)? I googled a lot but I did not quite find what I wanted. Maybe I also have an error in reasoning here on how to use transactions in firebase. One workaround might be to create an array of DocumentReference
s before the transaction and then use it transaction.getAll()
but that does not appear very elegant.
I will be thankful for any help :)
Best regards