Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method to iterate through all documents in a collection in firestore

I'm using the firestore of firebase and I want to iterate through the whole collection. Is there something like:

db.collection('something').forEach((doc) => {
  // do something
})
like image 771
Chang Avatar asked Jan 29 '18 05:01

Chang


People also ask

What are FireStore sub-collections and how do they work?

I’d like to talk at a high level about Firestore sub-collections. First, we need to review the Firestore data model. Firestore is a document/collection database. Documents hold whatever JSON data you’d like, but they must live within a collection. A document can have any number of sub-collections with their own documents.

How is data stored in Cloud Firestore?

As detailed in the Cloud Firestore documentation, data in Firestore is stored into documents, which are “organized into collections”. Documents can contain subcollections which, in turn, can contains documents. The documentation also indicates that:

What is the FireStore data model?

First, we need to review the Firestore data model. Firestore is a document/collection database. Documents hold whatever JSON data you’d like, but they must live within a collection. A document can have any number of sub-collections with their own documents. And you can keep nesting your data within sub-collections to your heart’s content.

How do I get the value of the FireStore document path?

We use the data parameter to get docPath, the value of the Firestore document path (slash-separated). This value is passed from the client calling the Cloud Function (see below). We then call the asynchronous listCollections () method on the DocumentReference created by using docPath (i.e. admin.firestore ().doc (docPath) ).


2 Answers

Yes, you can simply query the collection for all its documents using the get() method on the collection reference. A CollectionReference object subclasses Query, so you can call Query methods on it. By itself, a collection reference is essentially an unfiltered query for all of its documents.

Android: Query.get()

iOS/Swift: Query.getDocuments()

JavaScript: Query.get()

In each platform, this method is asynchronous, so you'll have to deal with the callbacks correctly.

See also the product documentation for "Get all documents in a collection".

like image 126
Doug Stevenson Avatar answered Sep 19 '22 04:09

Doug Stevenson


db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
});
like image 39
basickarl Avatar answered Sep 21 '22 04:09

basickarl