Reputation: 85
I want to count the number of branches of all restaurants. "Branch" is a sub collection of "Restaurants". When I try to do this query, there is an error:
rest.collection is not a function
Here's my code. How can I fix it?
async function getBranch(){
const size = 0;
const restRef = await firebase.firestore().collection('Restaurants').get();
restRef.forEach((rest) => {
const branchRef = rest.collection('Branch').get();
size = size + branchRef.size();
})
return size;
}
Upvotes: 0
Views: 229
Reputation: 83181
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;
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.
Upvotes: 0
Reputation: 6919
you have to provide id of restaurants to get the subcollection. So better make reference for Restaurants
and get all branches
async function getBranch(){
const size = 0;
const restRef = firebase.firestore().collection('Restaurants');
const restRes = await restRef.get();
restRef.forEach((rest) => {
const branchRef = await restRef.doc(rest.id).collection('Branch').get();
size = size + branchRef.size();
})
return size;
}
Upvotes: 1