1

I'm using Firestore as my NoSQL database and have struggled to try to work out the best structure to allow querying to conditionally send batched push notifications.

Previously I had this type of NoSQL structure (collection/doc/subcollection/doc):

users/ <-- root collection
  [userId]
    { push token }
    items/ <-- sub collection
      [itemId]
        { item data }

I would store the user push token at the users/[userId] level but the actual data for the user in the sub-collection.

The issue I found was querying across all users depending on the data in their sub-collection.

My next solution was to move the sub-collections to their own root collection, and each document has a reference to the users/[userId] that the data belonged to.

users/
  [userId]
    { push token }
items/
  [itemId]
    { item data, [userId] }

This would allow me to run the following logic in a cloud function:

  1. Store push tokens in a users root collection
  2. Fetch all user docs that have a stored push token
  3. Loop over the above user ids, and conditionally fetch item data that share a user id

Is this a good structure for working out which users you need to send a push notification to?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Dan Page
  • 75
  • 2
  • 8

1 Answers1

1

In the NoSQL world, we are structuring a database schema according to the queries that we want to perform. If you're asking if it's better to store the documents in a top-level collection vs. a sub-collection, then please check my answer from the following post:

So none of those two solutions is better than the other in terms of speed of costs. Regarding speed, Firestore is as fast at level 1 as it is at level 100. Regarding costs, everything in Firestore is about the number of reads you perform. So it doesn't really matter if your query returns N documents from a collection or the same N documents from a sub-collection, the cost will always be the same.

So if one of the schemas you mentioned in your question satisfies your needs, then you can go ahead with it.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • 1
    Yeh I guess this answers my question of basically do what you want. I guess I was hoping for best practice as I imagine every app that has push notifications will run into this question. – Dan Page Nov 25 '22 at 09:20