What’s up guys, Eze is here. I already did a couple of posts about Firebase and how to use the real-time database and storage with Angular. In case you missed it, you can check them out here. Today, I want to go further and show you how to structure your data. More importantly, we'll cover how to de-normalize your data. No, I'm not crazy. We are going to go in the exact opposite direction from what we learned with relational databases.
I guess this is the case for everyone who has some knowledge of relational databases. One of the first things we learn is how to normalize our database to reduce data duplication. In this post, I'm not saying we need to forget it — because if you are working with a relational database, it's the way to go — but with NoSQL databases, things are quite different.
Denormalization: Duplicating Data
Yes, as simple as that, denormalization means that we are going to duplicate data in order to simplify or minimize our queries. Let's take this model, for example.
In this model, we need to query our database twice to get both the order data and the user data. And that's fine as long as the query runs over a small dataset or is not going to run very often. But if that's not the case, you'll probably want to remove the inner query for good.
So taking this into account, one possible solution might be to store the user data we want to use like first name and last name under the order object instead of the reference id we are storing right now.
A Rule for Denormalization
Basically, a good rule to know when it's useful to denormalize our data structure is to design our database after our views. Doing that, we guarantee that, by using a single path, we will get the right data to show in our views. That also gives us the opportunity to do further queries in case we need them.
By this time, I'm sure you're wondering: What about consistency? And you are right, we are duplicating data everywhere. So, how can we guarantee consistency across our database? Firebase has that covered with a really good feature called multi-path updates, which I'm going to cover soon.
If you found this post useful, please don't forget to press the like button and share it. If you are in doubt, don't hesitate to ask a question and, as always, thank you for reading.