Array or Subcollection for storing events user uploaded

I’m creating an events app with react native. I just wanted some advice on which would be the better more performant and scalable way to structure my data model in firestore.
I have 2 collections Events and Users.

A user creates an event which goes into the Event collection, In my app users can then go onto the main page and view a list of events from the events collection.
I also want to have a second page in the app a “users profile” page where users can view a list of their own events, update and delete them.
My question is which would be better:

  1. to store the event’s key in an array in users/user1
  2. store basically a duplicate event in a subcollection called events in users/user1

I feel that option 1, might be better just to store a reference to the doc in an array, So I don’t have duplicates of the event and if the user has to update the event, only 1 write has to be made to the actual event in the events collections.

the event is likely to have more fields come onto it in the future, like a comments field etc, so I feel by just going with option 1 I dont have to keep doing double work, although I might have to read twice i.e read users/user1- > (then array) events:[event:{dockey}], then use that key to get the actual event doc in the events collection.

Thank you for any feedback and advice

Answer

There is no simple right or wrong answer when you need to choose between these two options. Data duplication is the key to faster reads, not just in Firebase Realtime Database or Cloud Firestore, but in general. Any time you add the same data to a different location, you’re duplicating data in favor of faster read performance. Unfortunately in return, you have a more complex update and higher storage/memory usage. But you need to note that extra calls in the Firebase Realtime Database are not expensive, in Firestore are. How much duplication data versus extra database calls is optimal for you, depends on your needs and your willingness to let go of the “Single Point of Definition mindset”, which can be also called very subjective.

After finishing a few Firebase projects, I find that my reading code gets drastically simpler if I duplicate data. But of course the writing code gets more complex at the same time. It’s a trade-off between these two and your needs that determines the optimal solution for your app.

Please also take a look at my answer from this post where I have explained more about collections, maps and arrays in Firestore.

Leave a Reply

Your email address will not be published. Required fields are marked *