'Firebase Firestore transactions on cloud functions ( getAll method on the callback function first param ) How to use it?
I've been struggling for a while to find out how exactly to use the getAll function on the first param of the callback function on runTransation function.
The doc firebase doc only shows how to use the get function to retrieve a single doc, but I want to retrieve multiple docs based on multiple where statements from a collection.
the question is how to use getAll function bellow?
export const match = functions.firestore
.document('waitingList/{userId}').onCreate(async (snapshot, context) => {
app.firestore().runTransaction(async transaction => {
transaction.getAll( //?); // ???
});
});
UPDATE 1 | 23/4/2022
I figured out a way (but I'm not fully satisfied with it because of duplication in reading from firestore).
The solution is as follows
app.firestore().runTransaction(async transaction => {
const docRefs: FirebaseFirestore.DocumentReference<any>[] = [];
(await firestore
.collection('collectionName')
.limit(100)
.get())
.forEach((doc) => {
docRefs.push(doc.ref);
}); //This is reading the Database for 100 docs
const users = await transaction.getAll(...docRefs); // This also is reading the database for the same 100 docs (But in a transaction context)
});
if someone knows how to read the docs only once in the transaction please do provide the solution.
Solution 1:[1]
Something like that:
transaction.getAll(...docRefs).then((docs) => {
docs.forEach((doc) => {/*...*/}
}
Solution 2:[2]
As @Abobker already stated, I agree that for now this will be the best way to retrieve multiple docs based on multiple where statements from a collection:
app.firestore().runTransaction(async transaction => {
const docRefs: FirebaseFirestore.DocumentReference<any>[] = [];
(await firestore
.collection('collectionName')
.limit(100)
.get())
.forEach((doc) => {
docRefs.push(doc.ref);
}); //This is reading the Database for 100 docs
const users = await transaction.getAll(...docRefs); // This also is reading the database for the same 100 docs (But in a transaction context)
});
Although is not the most efficient solution, It does address the problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
