Firebase database is a NoSQL database that stores its data in the form of hierarchal JSON objects. There are no tables or records of any form as an SQL database would normally have, just nodes that make up a key-value structure.
In order to have a properly designed database structure, the data requirements must be thoroughly outlined and forethought. The structure in this case should be normalized; the more flat the JSON tree, the faster data-access is.
Do's and Don'ts
The Wrong Way
Consider the following structure
This is a great example of what NOT to do. Multi-nested structures such as the one above can be very problematic and could cause a huge performance setback.
The way Firebase accesses a node is by downloading all the children's data, then iterating over all same-level nodes (all parents' children). Now, imagine a database with several users, each having hundreds (or even thousands) of posts. Accessing a post in this case could potentially load hundreds of megabytes of unused data. In a more complicated application, the nesting could be deeper than just 4 layers, which would result in more useless downloads and iterations.
The Right Way
Flattening the same structure would look like this
This spares a huge amount of overhead by iterating over less nodes to access a target object. All users that do not have any posts would not exist in the posts branch, and so iterating over those users in the wrong way above is completely useless.
The following is an example of a simple and minimal college database that uses two-way relationships
Note that each student has a list of courses and each course has a list of enrolled students.
Redundancy is not always a bad approach. It's true that it costs storage space and having to deal with multiple entries' updating when deleting or editing a duplicated node; however, in some scenarios where data is not updated often, having two-way relationships could ease the fetching/writing process significantly.
In most scenarios where an SQL-like query seems needed, inverting the data and creating two-way relationships is usually the solution.
Consider an application using the database above that requires the ability to:
- List the courses a certain student is taking and...
- List all the students in a certain course
If the database structure had been one-directional, it would incredibly slower to scan or query for one of the two requirements above. In some scenarios, redundancy makes frequent operations faster and much more efficient which, on the long run, makes the duplications' cost negligible.