How do you structure your data in your Firebase Database?

First Published: 13 October 2016
Updated on: 17 June 2019

Have you worked with Firebase Database yet? I don’t know about your background, but when I decided to give Firebase a shot I had spent years using PostgreSQL, so I came from a very SQL experience, and Firebase data structure was entirely new to me.

I was trying to do a lot of things in the SQL way (like normalization) until I realized that it doesn’t work that way, Firebase is different.

So today I wanted to give you a small tip:

It’s OK (in fact, it’s a best practice) to repeat data in Firebase.

The best way to structure your data in Firebase is making sure it’s easy to read later, this mind sound weird at first, but it is brilliant, for example:

Let’s say I have an app that shows a category list and the products for each category (keeping in mind a product can be in multiple categories)

In the SQL-like way, you might try to do something like this:

{
  "categories": {
    "tech": {
      "products": {
        "iPhone5": true
      }
    }
  },
  "products": {
    "iPhone5": {
      // Data about the phone here
    }
  }
}

And then when you call the product list and want more information about that product you take its ID and make a second call to the database to fetch the product matching that ID to get all its data.

But if you optimize your DB for reading, you might want to repeat some data:

{
  "categories": {
    "tech": {
      "products": {
        "iPhone5": {
          "color": "white"
          "price": 700
        }
      },
    },

  },
  "products": {
    "iPhone5": {
        // Data about the phone here
    }
  }
}

That way when you call the category list and then need more information about the product the data is already there, this is good for two things:

Text is cheap. It won’t take a lot of space in the Firebase database.

You aren’t making new database requests, so you aren’t abusing your user’s data plan.