0
votes

I read several documentation but I don't understand why I should use an extra layer(foreach) in my code when I read all of the data inside a collection using Firebase (Cloud Firestore).

Here is the original documentation:
https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection

Here is my code:

  async loadUsers(): Promise<User[]> {
    const users = new Array<User>();
    const snapshot = await this.firestore.collection('users').get();
    snapshot.forEach((collection) => {
      collection.docs.forEach(doc => {
        users.push(doc.data() as User);
      });
    });
    return users;
  }

As I understand it should work like this:

async loadUsers(): Promise<User[]> {
    const users = new Array<User>();
    const snapshot = await this.firestore.collection('users').get();
    snapshot.forEach(doc => {
      users.push(doc.data() as User);
    });
    return users;
  }

Error message:
"Property 'data' does not exist on type 'QuerySnapshot'."

2
I'm confused. Your first code sample doesn't look at all correct. If all you're trying to do is iterate documents in a collection, you don't need a second forEach loop. The second code sample looks correct. Please edit the question to explain in more detail what isn't working the way you expect. - Doug Stevenson
@DougStevenson Yes, you are right, the first code sample doesn't look good, but it's work somehow and the second does not. This is what I want to understand... why? - Balázs Fodor-Pap

2 Answers

2
votes

.collection().get() does NOT return an array; it returns a QuerySnapshot, which has a property .docs, which is an array of QueryDocumentSnapshot, each of which has a property .data, which is the data read from the document.

Documentation https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference

0
votes

Based on @LeadDreamer answer, I could manage to simplify the code

  async loadUsers(): Promise<User[]> {
    const users = new Array<User>();
    await this.firestore.collection('users').get().subscribe(querySnapshot => {
      querySnapshot.docs.forEach(doc => {
        users.push(doc.data() as User);
      });
    });
    return users;
  }