Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore - Get document collections

I would automate the backup process of a firestore database.

The idea is to loop over the root document to build a JSON tree, but I didn't find a way to get all collections available for a document. I guess it's possible as in firestore console we can see the tree.

Any ideas?

  • ref doc: https://firebase.google.com/docs/reference/js/firebase.firestore
like image 630
eskan Avatar asked Oct 28 '17 12:10

eskan


People also ask

How do I get data from QueryDocumentSnapshot?

A QueryDocumentSnapshot contains data read from a document in your Cloud Firestore database as part of a query. The document is guaranteed to exist and its data can be extracted using the getData() or the various get() methods in DocumentSnapshot (such as get(String) ).

How do I query Subcollection in firestore?

You can either go to Firestore Databases > Indexes console and do it, or use the firebase cli. But the easiest option is to just let your code (that performs the query) run and firestore will automatically error out when an index is missing.


2 Answers

Its possible on web (client side js)

db.collection('FirstCollection/' + id + '/DocSubCollectionName').get().then((subCollectionSnapshot) => {
    subCollectionSnapshot.forEach((subDoc) => {
        console.log(subDoc.data());
    });
});

Thanks to @marcogramy comment

like image 166
Daniel Avatar answered Oct 18 '22 23:10

Daniel


Update
API has been updated, now function is .listCollections() https://googleapis.dev/nodejs/firestore/latest/DocumentReference.html#listCollections


getCollections() method is available for NodeJS.

Sample code:

    db.collection("Collection").doc("Document").getCollections().then((querySnapshot) => {
    querySnapshot.forEach((collection) => {
        console.log("collection: " + collection.id);
        });
    });
like image 39
Mike Yang Avatar answered Oct 18 '22 22:10

Mike Yang