Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore collection retrieval in React Native

I'm building a React Native app with Expo using the Firebase web api and trying to retrieve a collection of documents from my Firestore project. According to the documentation over at https://firebase.google.com/docs/firestore/query-data/get-data I should be able to iterate over a collection using the forEach() method provided by the collection snapshot like so:

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

This however only logs one document, despite the fact that I currently have 3 documents in the collection, what am I missing? Please help.

My firebase config looks like so:

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();
like image 243
Pip Avatar asked Oct 08 '17 14:10

Pip


1 Answers

I finally got it after a bit debugging. Looks like what I needed to do was use the _document.data property on each snapshot returned by the forEach on the querySnapshot. So my code now looks like so:

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

This feels like a bit of a hack but logging just doc._document.data returns a lot of metadata along with each document, toString() returns just the document data but as a JSON string so then I parse it into a JavaScript object with JSON.parse.

like image 196
Pip Avatar answered Sep 22 '22 15:09

Pip