【问题标题】:Can't fetch Firestore subcollection [closed]无法获取 Firestore 子集合 [关闭]
【发布时间】:2020-01-16 12:03:45
【问题描述】:

我正在使用 React + Firebase 中的应用程序。我的问题是子集合数据未定义

我的 Firestore 收藏:

users - XXXXXXXXXX - name: xxxxx
                   ├ image: xxxxx
                   └ shifts - monday - before_noon: true
                                     ├ after_noon: false
                                     └ night: true

错误:

无法读取未定义的属性“星期一”

我的代码:

{user.shifts.monday.before_noon}

如何在 Firestore 中调用子集合下的数据。

【问题讨论】:

  • shiftsuser 文档的子集合的名称吗?另外,您能否分享您用来获取user 文档的代码(没有shifts)?

标签: reactjs firebase google-cloud-firestore


【解决方案1】:

子集合与 Firestore 文档中的嵌套数据不同。对于嵌套数据,您可以从单个文档获取中访问所有内容。示例:

const db = firebase.firestore();

await db.collection('users').doc('alice').set({
  name: 'Alice',
  shifts: {
    monday: {before_noon: true}
  }
});

// this is "true"
await db.collection('users').doc('alice').get()).data.shifts.monday.before_noon;

另一方面,子集合是完全独立的文档集合,在逻辑上与父文档相关。您必须从其父文档中单独获取子集合:

const userRef = db.collection('users').doc('alice');
const shiftsRef = userRef.collection('shifts');

await shiftsRef.doc('monday').set({
  before_noon: true
});

(await userRef.get()).data() // does not include .shifts
(await shiftsRef.get()).docs.map(snap => {
  day: snap.id, data: snap.data()
}); // [{day: 'monday', data: {before_noon: true}}]

一般而言,嵌套数据应在数量有限且您几乎总是希望与其余数据一起获取时使用。 子集合应在有大量嵌套数据(即太大而无法放入文档中)或数据并不总是需要与父数据一起获取时使用。

【讨论】:

  • 非常感谢迈克尔。这真的很有帮助,我可以理解 firestore 子集合的工作原理。
猜你喜欢
  • 2021-05-07
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 2018-03-18
  • 1970-01-01
相关资源
最近更新 更多