Field groups
Even though it’s intuitive to keep documents as flat as possible, just like you would do in a traditional SQL database, it’s not always the best idea with Firestore.
Consider the given example where we have a blog post that can be soft deleted, and we want to know who deleted it:
Updating such a document with only one of the fields will not cause a type error:
So, if we would want to make sure these are always set together and keep the structure flat, we would need to intersect the types:
It’s already messy, but even though we just have three fields! Imagine how it would look with more conditional fields.
There’s another problem: since it’s a union, we can’t access deletedAt
without the property check:
Having such types will quickly turn your database and codebase into a mess.
The better approach is to group fields into a separate object:
Now, we are forced to assign both fields together, and also we can access them without a property check:
Neat!
Fields groups allow you to define relations between fields, which leads to better type safety and readability. Since there’s no penalty for nesting objects in Firestore, whenever you feel you might need group fields - go for it!
Furthermore, it enables you to share such groups with other models, making your database more consistent and easier to maintain: