Lehar001
Lehar001

Reputation: 73

Optimal relational data model in Firestore

I have a set of static and pre-defined to-do's that each user in my app needs to be able to set as completed on their account.

At the moment, I use a map on the todo item that specifies which users has completed the task. My data model at the moment looks like this:

- todos (collection)
  - todoA (document)
    - title, description etc
    - completedBy {
       uid1: true,
       uid2: true,
       uid3: false
      }

This allows me to easily set todos as completed/not completed for each user and I can easily filter/query. It does have two drawbacks though:

  1. A single Firestore document can "only" have 20 000 properties. If my app would grow large, this would be an issue.
  2. Document size

I was thinking of maybe creating a similar map on my user document instead, setting todo ID's as true/false. This would get rid of the two drawbacks above but I'd need two database queries whenever I'm getting my todo items, one for the todo and one to check if it's completed.

Is there a better way to achieve the desired functionality in Firestore?

Upvotes: 0

Views: 431

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599041

If you are running into either the maximum number of fields or the maximum document size, then typically that means that you should be using a separate collection for "the thing that makes your documents so big".

In your case that'd mean that you store the "user has completed a task" in a separate collection. This can be a subcollection of the user document, a subcollection of the task document, and/or a separate top-level collection. Which one is correct depends on your use-case.

There is no single best data model in NoSQL databases. It all depends on your use-cases, trade-offs, and some personal preferences. For a great introduction read NoSQL data modeling and watch Get to Know Cloud Firestore.

Upvotes: 1

Related Questions