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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With