4

I have a nested collection in firestore as shown below:

db-dev
        user
             user-id-1
                       events-collection
                       ...
             user-id-2
                       events-collection
                       ...
             user-id-3
                       events-collection
                       ...

I want to query all the events from events-collection. However, I also want to keep the above schema as the admin needs to view all events-collection and specific users need to view their specific collection.

The query I write now looks something like this:

const uids = await getAllUserIds(); //Returns all user ID
const promises = uids.map(element => db.collection(`db-dev/user/${element}/events-collection/`).get())

const documents = await Promise.all(promises);

I am not very confident if this is the most optimized way to query the data or should I use something else? Can somebody please help me out here?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Shivam Sahil
  • 4,055
  • 3
  • 31
  • 62
  • 1
    If you are interested, you can also check the following article, [How to query collections in Firestore under a certain path?](https://medium.com/firebase-developers/how-to-query-collections-in-firestore-under-a-certain-path-6a0d686cebd2). – Alex Mamo Feb 08 '22 at 15:17

1 Answers1

6

To read from all events-collection collections in one go, you can use a collection group query.

For example, without any conditions, this reads all documents from all collections named events-collection:

db.collectionGroup('events-collection').get()

If you want to read only the events-collection collections under /user, you can use the trick that Sam showed here: CollectionGroupQuery but limit search to subcollections under a particular document

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807