Firebase Functions:如何通过单次调用获取所有子集合?
问题:Firestore能否通过一次调用获取文档及其所有子集合数据?
我用firebase-admin操作Firestore,在users集合下的指定用户文档里有internProps、externProps、geoPath三个子集合。现在要通过四次数据库调用分别获取用户文档和三个子集合的数据,代码如下:
const profile = await admin .firestore() .collection("users") .doc(context.auth.uid) .get(); const internProps = await admin .firestore() .collection("users") .doc(context.auth.uid) .collection("internProps") .get(); const externProps = await admin .firestore() .collection("users") .doc(context.auth.uid) .collection("externProps") .get(); const geoPath = await admin .firestore() .collection("users") .doc(context.auth.uid) .collection("geoPath") .get();
四次调用的数据库开销有点高,想问下能不能只调用users集合就提取所有子集合的数据?还是必须分三次调用获取子集合?
回答
不行,Firestore的设计就是文档和子集合是完全独立的存储单元,获取父文档的操作不会自动拉取它的子集合数据。
你必须单独发起请求来获取每个子集合的内容,但可以做个关键优化:把三个子集合的请求改成并行发起,而不是串行等待,这样能大幅减少整体的等待时间。用Promise.all就能实现:
const userId = context.auth.uid; const userDocRef = admin.firestore().collection("users").doc(userId); // 并行发起所有请求,同时执行而非逐个等待 const [profileSnap, internPropsSnap, externPropsSnap, geoPathSnap] = await Promise.all([ userDocRef.get(), userDocRef.collection("internProps").get(), userDocRef.collection("externProps").get(), userDocRef.collection("geoPath").get() ]); // 整理数据(保留文档ID方便后续操作) const profile = profileSnap.data(); const internProps = internPropsSnap.docs.map(doc => ({ id: doc.id, ...doc.data() })); const externProps = externPropsSnap.docs.map(doc => ({ id: doc.id, ...doc.data() })); const geoPath = geoPathSnap.docs.map(doc => ({ id: doc.id, ...doc.data() }));
这样还是四次请求,但它们是同时进行的,总耗时会接近最慢的那一个请求的时间,比串行执行高效很多。
另外,如果你想从根源上减少请求次数,可以考虑调整数据结构:
- 如果子集合的数据量不大,且总是和父文档一起读取,可以把子集合的内容直接作为父文档的数组或对象字段存储
- 但如果子集合文档数量多、需要单独查询/更新单个子文档,或者数据结构复杂,保留子集合的设计会更合理,这需要根据你的业务访问模式来权衡。
内容的提问来源于stack exchange,提问作者reactnative_newbie
相关产品推荐
相关产品推荐

