2017-10-08 117 views
2

我正在使用Firebase Web API构建一个React Native应用程序,并尝试从我的Firestore项目中检索文档集合。根据该文件在在https://firebase.google.com/docs/firestore/query-data/get-data我应该能够使用收集快照像这样提供在foreach()方法来遍历集合:React Native中的Firebase Firestore集合检索

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

但是,这仅记录一个文档,尽管我目前收藏中有3个文件,我错过了什么?请帮忙。

我的火力配置看起来像这样:

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();

+0

是其他两个文件是空的?你能发送你的数据库结构的屏幕截图吗? – tugce

+0

@tugce我在其他两个文档中有数据,当我只记录文档ID或元数据时,它全部显示在我的控制台中,当我调用只有一个文档显示的data()方法时。 – Pip

回答

0

我终于有点经过调试。看起来我需要做的是对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对象。