首页 文章

React Native中的Firebase Firestore集合检索

提问于
浏览
3

我正在使用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());
    }
  });
});

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

我的firebase配置如下所示:

import * as firebase from 'firebase';
 firebase.initializeApp({
    "projectId": "my-project-id",
    "apiKey": "my-api-key",
    "authDomain": "my-project.firebaseapp.com",
    "databaseURL": "https://my-project.firebaseio.com",
    "storageBucket": "my-project-id.appspot.com/",
    "messagingSenderId": "my-messaging-sender-id"
})
const db = firebase.firestore();

2 回答

  • 1

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

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

    这感觉就像是一个黑客,但只是 doc._document.data 返回大量的元数据和每个文档,toString()只返回文档数据,但作为一个JSON字符串,然后我用JSON.parse解析它到一个JavaScript对象 .

  • 0

    或者,您也可以使用像firestorter这样的lib将Firestore无缝集成到React中

    https://medium.com/@hrutjes/building-a-react-firestore-app-with-zero-effort-and-mobx-525df611eabf

相关问题