You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase中如何不指定路径名称获取所有二级及三级文档?

Firebase中跨未知路径的文档查询方案

问题描述

我想获取所有二级文档,但一级路径是可变的(未知),具体需求如下:

getDocs(query(collection(db, "users", unknownCities, unknownSchools), where("gender","==", "female") ))  

其中users是集合,unknownCities是文档,unknownSchools是集合,后续是包含gender字段、名为userIds的文档。想实现类似安全规则里{path=**}的通配符效果,请问这在Firebase中可行吗?

答案

Firebase Firestore不支持直接用通配符替代路径中的未知文档/集合节点,没法像安全规则那样通过{path=**}直接跨所有未知路径查询。要实现需求,有两种可行思路:

思路1:分步查询遍历

先获取所有unknownCities的文档ID,再逐个遍历查询对应的unknownSchools集合:

// 第一步:获取users集合下所有城市文档
const citiesSnapshot = await getDocs(collection(db, "users"));
const femaleUsers = [];

// 第二步:遍历每个城市,查询对应的学校集合
for (const cityDoc of citiesSnapshot.docs) {
  const schoolsRef = collection(db, "users", cityDoc.id, "unknownSchools");
  const querySnapshot = await getDocs(query(schoolsRef, where("gender", "==", "female")));
  
  querySnapshot.forEach(doc => {
    femaleUsers.push({ id: doc.id, ...doc.data() });
  });
}

// 最终femaleUsers就是所有符合条件的文档数据

这种方法的缺点是如果城市数量较多,会发起多次查询,需要注意性能和并发限制。

思路2:重构数据结构

如果业务允许,建议调整数据结构,把用户数据直接放在一个集合里,用city和school作为字段标记,比如:

users -> {userId}
  - gender: "female"
  - city: "Beijing"
  - school: "No.1 High School"

这样查询就简单多了,直接一次过滤:

const q = query(collection(db, "users"), where("gender", "==", "female"));
const querySnapshot = await getDocs(q);

这种方式更符合Firestore的设计理念,查询效率也更高。

内容的提问来源于stack exchange,提问作者JeremyFc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 18:02:21