Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list subcollections in a Cloud Firestore document

Say I have this minimal database stored in Cloud Firestore. How could I retrieve the names of subCollection1 and subCollection2?

rootCollection {
    aDocument: {
        someField: { value: 1 },
        anotherField: { value: 2 }
        subCollection1: ...,
        subCollection2: ...,
    }
}

I would expect to be able to just read the ids off of aDocument, but only the fields show up when I get() the document.

rootRef.doc('aDocument').get()
  .then(doc =>

    // only logs [ "someField", "anotherField" ], no collections
    console.log( Object.keys(doc.data()) )
  )
like image 727
skylize Avatar asked Oct 06 '17 00:10

skylize


People also ask

How do I get specific data from firestore?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.


2 Answers

In Node.js you'll be after the 'ListCollectionIds' method

var firestore = require('firestore.v1beta1');

var client = firestore.v1beta1({
  // optional auth parameters.
});

// Iterate over all elements.
var formattedParent = client.anyPathPath("[PROJECT]", "[DATABASE]", "[DOCUMENT]", "[ANY_PATH]");

client.listCollectionIds({parent: formattedParent}).then(function(responses) {
    var resources = responses[0];
    for (var i = 0; i < resources.length; ++i) {
        // doThingsWith(resources[i])
    }
})
.catch(function(err) {
    console.error(err);
});

This is not currently supported in the client SDKs (Web, iOS, Android).

like image 114
Dan McGrath Avatar answered Oct 01 '22 09:10

Dan McGrath


It seems like they have added a method called getCollections() to Node.js:

firestore.doc(`/myCollection/myDocument`).getCollections().then(collections => {
  for (let collection of collections) {
    console.log(`Found collection with id: ${collection.id}`);
  }
});

This example prints out all subcollections of the document at /myCollection/myDocument

like image 43
0xC0DEBA5E Avatar answered Oct 01 '22 10:10

0xC0DEBA5E