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

如何从Firebase Observable集合中获取文档ID?

解决Firebase查询无法获取文档ID的问题

问题出在你使用的collectionData方法默认只返回文档内容数据,不会包含文档ID。要同时获取ID,只需给collectionData添加配置参数,指定ID字段的名称即可。

第一步:修改服务中的查询方法

更新getdata方法,在collectionData中加入{ idField: 'id' }配置,这样返回的每个文档对象都会带上名为id的字段,对应文档ID:

getdata(uid: string): Observable<any> {
  const iQuery: Query<DocumentData> = query(
    collection(this.firestore, 'collection'),
    where('userInfo.userId', '==', uid)
  );

  // 添加idField配置,将文档ID注入返回数据中
  return collectionData(iQuery, { idField: 'id' });
}

第二步:在调用处获取文档ID

修改后,订阅Observable得到的数组中,每个元素都会包含id字段,直接访问即可:

// ngOnInit中的调用代码
this.itineraryQuery(this.userInfo.uid).forEach(
  docs => {
    this.myItineraries = docs;
    // 示例:打印每个文档的ID和内容
    // docs.forEach(doc => console.log(doc.id, doc));
  }
);

为什么之前的方法无效?

你之前习惯用snap.data()和snap.id,是因为那是直接处理QuerySnapshot或DocumentSnapshot对象的方式。但collectionData是AngularFire提供的便捷方法,它已经帮你提取了每个文档的data()结果,默认不会包含ID,必须通过配置参数显式开启。

内容的提问来源于stack exchange,提问作者D.Hodges

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:24:25