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

如何使用AngularFire基于Firestore文档引用数组获取指定集合文档?

高效查询Cloud Firestore中引用数组指向的文档

Firestore 提供了内置的__name__字段来实现这类需求,你可以直接基于这个字段做in查询,无需额外存储路径或ID字段,这是比getAll()更高效的批量查询方式。

核心原理

每个Firestore文档的__name__字段对应其完整的文档路径(和DocumentReference的路径完全一致),你可以直接用这个字段作为查询条件,传入DocumentReference数组进行匹配。

实现代码(TypeScript)

getBs(bRefs: DocumentReference<B>[]) {
  // Firestore的in查询最多支持10个元素,超过需分批处理
  if (bRefs.length > 10) {
    const batches = [];
    for (let i = 0; i < bRefs.length; i += 10) {
      const batch = bRefs.slice(i, i + 10);
      batches.push(
        this.fstore.collection<B>('b', ref => ref.where('__name__', 'in', batch)).get()
      );
    }
    return Promise.all(batches).then(results => {
      const docs: QueryDocumentSnapshot<B>[] = [];
      results.forEach(snapshot => docs.push(...snapshot.docs));
      return { docs };
    });
  }
  
  return this.fstore.collection<B>('b', ref => ref.where('__name__', 'in', bRefs)).get();
}

注意事项

  • 查询限制:in查询最多只能包含10个元素,若bRefs数组长度超过10,必须拆分成分批查询后合并结果。
  • 性能优势:这种方式比getAll()更高效,每批查询是单个请求获取多个文档,而getAll()是对每个文档发起独立请求,批量查询的请求数更少。
  • 索引说明:__name__字段无需手动创建索引,Firestore默认支持对该字段的查询。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 03:46:15