Jakob
Jakob

Reputation: 4854

firestore query in subcollection

Alright, so I'm building a new app, and with GDPR and all I have chosen to structure my data with UserID's at the toplevel, so deleting all data for a user becomes extremely easy.

This unfortunately means that other operations become a bit harder, but I'm hoping that with firestore's data-structure there's a way to solve my issue.

I am logging a series of checkins, the structure looks like this: checkins/{userid}/log/{checkin} The checkin object contains a space_id, which correlate to another top level collection called spaces.

Now I want to count the number of checkins made by ALL users in a selected space, but I don't know how I would ask firebase to look at ALL userid/log/checkin's and find the one's with space_id = x.

Is there a neat and efficient way to do this?

Upvotes: 3

Views: 5833

Answers (2)

John Doee
John Doee

Reputation: 145

Update: As of May, 2019, Cloud Firestore now supports collection group queries.

In my opinion this is one of the major weaknesses in Firestore. While the documentation emphasizes its support for more complex data structures than firebase you are still somehow required to use a flattened data scheme in order to query those structures.

What you are searching for is a so-called Collection Group Query (see Firestore query subcollections)

In your current design you would have to query all checkins and subsequently query on all of them for the space id.

In your position I would make use of a top-level structure as the processes of user data gathering (GDPR) are probably rare compared to casual operations.

Upvotes: 3

apaatsio
apaatsio

Reputation: 3793

Firebase supports collection group queries as of May 2019.

In this use case you can write:

db.collectionGroup('log')
  .where('space_id', '==', '123')
  .get()
  .then(function (querySnapshot) {
    console.log('Number of check-ins:', querySnapshot.size);
  });

Upvotes: 1

Related Questions