Javascript 子集合的firestore查询错误:rest.collection不是函数

Javascript 子集合的firestore查询错误:rest.collection不是函数,javascript,node.js,firebase,react-native,google-cloud-firestore,Javascript,Node.js,Firebase,React Native,Google Cloud Firestore,我想数一数所有餐馆的分店数目。“分行”是“餐厅”的子集合。尝试执行此查询时,出现错误: rest.collection不是一个函数 这是我的密码。我怎样才能修好它 异步函数getBranch(){ 常数大小=0; const restRef=wait firebase.firestore().collection('Restaurants').get(); restRef.forEach((剩余)=>{ const branchhref=rest.collection('Branch').get

我想数一数所有餐馆的分店数目。“分行”是“餐厅”的子集合。尝试执行此查询时,出现错误:

rest.collection不是一个函数

这是我的密码。我怎样才能修好它

异步函数getBranch(){
常数大小=0;
const restRef=wait firebase.firestore().collection('Restaurants').get();
restRef.forEach((剩余)=>{
const branchhref=rest.collection('Branch').get();
size=size+branchhref.size();
})
返回大小;
}

您必须提供餐厅id才能获得子集合。因此,最好参考
餐厅
,并获得所有
分支机构

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;
}

您可以使用(未测试)执行以下操作


然而, 您应该注意,这意味着每次要获取
分支
文档的数量时,您都要阅读所有(子)集合的所有文档,因此,这是有成本的

因此,如果您的集合中有大量文档,一种更经济的方法是维护一组保存文档数量的分布式计数器。每次添加/删除文档时,都会增加/减少计数器


有关更多详细信息,请参见文档中的。

Hi@Ashish,在forEach循环中不应使用async/wait,请参见循环中调用的回调函数,但它不会等待回调函数完成后再转到数组的下一个条目。看一看。要解决这个问题,请使用我在回答中指出的“技巧”(
Promise.all()
)或我在上面提到的一些答案中详述的其他技巧。
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;
}
const branchQS = await firebase.firestore().collectionGroup('Branch').get();
return branchQS.size;