How to get all documents of a collection of all documents of a collection?

Viewed 122

I'm trying to loop through all users (documents) in my user collection, and then access a collection in each user, where I will check if a field is set to true.

I am capable of looping through my users as follows:

  let users = await firebase
    .firestore()
    .collection("users")
    .get()

  return users.docs.map(item => item.data())

But I am incapable of reaching further and accessing the collection inside of each user document.

All examples for accessing subcollections I've seen online have involved explicitly doing so, i.e.

let snapshot = await firebase
    .firestore()
    .collection('users')
    .doc('exampleUID')
    .collection('subcollection')
    .get()

But I see no examples for guidance for getting collections for all documents inside a collection.

1 Answers

There is no single mechanism to simultaneously get a document, and all the "child" documents from all the "child" collections, but you can get all the documents in a sub-collection.

It's called "collectionGroups". You create a query on a CollectionGroup called subcollection. Works well.

firebase.firestore().collectionGroup(tableName).get()

Warning,though, - it treats ALL collections and sub-collections named subcollection together, regardless of level, so you do have to think about how you name your subcollections. If, for example, you tried .collectionGroup("thatGroup") and you had the following structures in your database:

/topCollection1/{documents}/subcollection1/{documents}/thatGroup/{documents}
/topCollection2/{documents}/thatGroup/{documents}

you would end up with documents that were descendants of topCollection1 and topCollection2.

And while the results are presented in a single QuerySnapshot, you can find out which path each resulting document came from using .ref.path (a string) and parsing it, or repeated use of .parent().

Related