3

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?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Jakob
  • 4,784
  • 8
  • 53
  • 79

2 Answers2

3

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.

Juan Lara
  • 6,454
  • 1
  • 22
  • 31
John Doee
  • 145
  • 1
  • 10
  • What are your thoughts on adding business logic to keep a counter in a seperate collection? Feels a bit too hackish for such a standard use case... – Jakob May 04 '18 at 10:16
  • I mean this would be a possible solution but the design really restricts you when it comes to possible features in the future. What if you want to find out which users have checked in at some point? Also you would have to implement a cloud function or a hook to subtract users who delete their account and so on. (And yes, its hackish. As described above, I would go for a flattened design. If you anyway want to implement the counter, do not create create a seperate collection but define it as a property of the spaces collection) – John Doee May 04 '18 at 11:11
  • Collection group queries are now available in Firestore. – Doug Stevenson May 08 '19 at 19:25
1

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);
  });
apaatsio
  • 3,073
  • 1
  • 22
  • 18