React Native 中的 Firebase Firestore 集合检索

Pip*_*Pip 6 firebase react-native expo google-cloud-firestore

我正在使用 Firebase Web api 使用 Expo 构建 React Native 应用程序,并尝试从我的 Firestore 项目中检索文档集合。根据https://firebase.google.com/docs/firestore/query-data/get-data上的文档,我应该能够使用集合快照提供的 forEach() 方法迭代集合,如下所示:

db
.collection('services')
.get()
.then(snapshot => {
  snapshot.forEach(doc => {
    if (doc && doc.exists) {
      console.log(doc.id, ' => ', doc.data());
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

然而,这仅记录了一个文档,尽管我目前在集合中有 3 个文档,但我错过了什么?请帮忙。

我的 firebase 配置如下所示:

db
.collection('services')
.get()
.then(snapshot => {
  snapshot.forEach(doc => {
    if (doc && doc.exists) {
      console.log(doc.id, ' => ', doc.data());
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

Pip*_*Pip 2

经过一番调试终于搞定了。看起来我需要做的是在 querySnapshot 上的 forEach 返回的每个快照上使用 _document.data 属性。所以我的代码现在看起来像这样:

db
    .collection('services')
    .get()
    .then(snapshot => {
      snapshot
        .docs
        .forEach(doc => {
          console.log(JSON.parse(doc._document.data.toString()))
        });
    });
Run Code Online (Sandbox Code Playgroud)

这感觉有点像黑客,但日志记录只是doc._document.data随每个文档返回大量元数据,toString() 仅返回文档数据,但作为 JSON 字符串,所以然后我使用 JSON.parse 将其解析为 JavaScript 对象。