FrankenSHTEIN
FrankenSHTEIN

Reputation: 23

How to get all documets from firestore

I want to get all documents from firestore. I tried to do this

const firestore = getFirestore()
firestore
  .collection('products')
  .limit(4)
  .get()
  .then((snapshot) => {
    dispatch({ type: 'SHOW', snapshot })
  })
  .catch((err) => {
    dispatch({ type: 'SHOW_ERROR', err })
  })

then i do this

case 'SHOW':
      console.log('SHow 4', action.snapshot.docs)

but as response i get this enter image description here How can i get the values of objects?

Upvotes: 0

Views: 39

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

From the doc:

A QuerySnapshot contains zero or more DocumentSnapshot objects representing the results of a query.

You therefore have to loop over the QuerySnapshot, as follows:

case 'SHOW':
    action.snapshot.forEach(doc => {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });

or, you loop in the callback function passed to the then() method:

firestore
  .collection('products')
  .limit(4)
  .get()
  .then((snapshot) => {
    snapshot.forEach(doc => {
        // do something
    });
  })
  .catch((err) => {...});

You can also loop over the JavaScript Array of all the documents in the QuerySnapshot that you get with action.snapshot.docs.

For example:

for (doc in action.snapshot.docs) {
    console.log(doc.data());
}

Upvotes: 1

Related Questions