You could do as follow, by using Promise.all()
(untested).
async function getBranch(){
let size = 0;
const restQS = await firebase.firestore().collection('Restaurants').get();
const promises = [];
restQS.forEach((rest) => {
promises.push(rest.collection('Branch').get());
});
const querySnapshotsArray = await Promise.all(promises);
querySnapshotsArray.forEach(qs => {
size += qs.size; // <= Note that size is a property of the QuerySnapshot, not a method
})
return size;
}
Another approach would be to query all your branch doc with a Collection group query, if the only collections named Branch
are subcollection of Restaurants.
const branchQS = await firebase.firestore().collectionGroup('Branch').get();
return branchQS.size;
HOWEVER,
you should note that this implies that you read ALL the documents of ALL the (sub)collections each time you want to get the number of branch
documents and, therefore, it has a cost.
So, if your collections have a lot of documents, a more affordable approach would be to maintain a set of distributed counters that hold the number of documents. Each time you add/remove a document, you increase/decrease the counters.
See here in the doc for more details, as well as this answer.