Skip to content
Advertisement

How can I count in Firebase the collections in a document

I know how to count how many Documents are in a collection in Firebase but how does it work the other way around. I have several collections in a document and I need to find out how many. (In my example it would be 2)

My Setup:

Collection     Document      Collections  Documents
[USERID]   -   [TESTS]   -   [1]   -      [ANSWERS]
                                          [RESULTS]
                         
                             [2]   -      [ANSWERS]
                                          [RESULTS]

I tried the following but it does not work:

let refTest_1 = db.collection(USERID).doc('TESTS')
let testData_1
refTest_1.get().then(doc => {
  //testData_1 = doc.data()
  testData_1 = doc.size
}).then(function() {
  //console.log(Object.keys(testData_1).length)
  console.log(testData_1)
}).catch(error => {
  console.log("Error: " + error.message)
})  

Does anybody know how this works?

Thanks!

Advertisement

Answer

The official Firebase Web Client has no implemented method to get all collections of an object. You can take a look at the documentation here. In Node.js you could just use the .listCollections() method as described in the same documentation. Afterwards, you would have to get all the documents in the collections and count them manually in js.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement