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
})
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.
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:
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.
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) ).
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".
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());
});
});
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