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

如何从Firestore获取完整数组而非返回对象?

如何从Firestore文档中提取数组数据?

你现在的代码已经成功拿到了Firestore文档的完整数据对象,要从中取出数组其实非常简单——核心就是访问文档对象中对应数组的字段名就行。

假设你的fragebogen1文档里,存储目标数组的字段叫yourArrayFieldName(比如实际场景可能是antworten、questions这类名字),只需要在获取到data之后,直接通过字段名提取即可。修改后的代码如下:

fb.usersCollection
  .doc(this.currentUser.uid)
  .collection('fragebogen')
  .doc('fragebogen1')
  .get()
  .then(snapshot => { 
    const data = snapshot.data() 
    // 把这里的yourArrayFieldName替换成你实际的数组字段名
    const targetArray = data.yourArrayFieldName; 
    console.log("提取到的目标数组:", targetArray);
    // 接下来就可以用targetArray做后续处理了
  })
  .catch(error => { 
    console.log("查询Firestore时出错:", error) 
  }) 

另外给你提个小建议:为了避免因为字段不存在或者文档为空导致报错,可以加个简单的判断,让代码更健壮:

fb.usersCollection
  .doc(this.currentUser.uid)
  .collection('fragebogen')
  .doc('fragebogen1')
  .get()
  .then(snapshot => { 
    const data = snapshot.data() 
    if (data && data.yourArrayFieldName) {
      const targetArray = data.yourArrayFieldName;
      console.log("提取到的目标数组:", targetArray);
      // 处理数组逻辑
    } else {
      console.log("文档为空,或者目标数组字段不存在");
    }
  })
  .catch(error => { 
    console.log("查询Firestore时出错:", error) 
  }) 

注意哦,Firestore的字段名是大小写敏感的,一定要和你在Firestore控制台里设置的字段名完全一致,不然会取不到数据~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:04:12