Miguel Stevens
Miguel Stevens

Reputation: 9230

Firebase, load related data?

I'm using a flat database layout with Products that have Users, the database layout looks like this. It's the commonly used 'flat' way of working with Firebase data.

Now I have a route, the user can visit: /products/1, which should load the users for that product

So basically I need to ask Firebase to give me the users details for that product's users. (so for 1 and 2 in my example)

What's the good way to go about this?

products: [
    {
        id: 1,
        name: 'Product One',
        users: [
            1: true,
            2: true

        ]
    } 
],
users: [
    {
        id: 1,
        name: Tom
    }
]

Upvotes: 0

Views: 101

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600006

There are two main options

  1. Load the data for each individual user as needed. This is known as a client-side join and is a quite common solution. The performance is not nearly as bad as many developers think, since the requests for the users are pipelined over the single existing connection. And you can of course deduplicate the requests, by keeping a cache of recently requested users.
  2. Duplicate the main data for each user under each product. For example: if you need to display the user name for each user with the product, you could store the name of each user under each product:

    products: [
        {
            id: 1,
            name: 'Product One',
            users: [
                1: "Tom",
                2: "Notflip"
            ]
        } 
    ],
    

    With this data structure you just have to load the product node, no joins (neither server-side nor client-side) is needed. If you come from a background in relational databases this probably sets off all your "normalization alarms", but in NoSQL databases this type of data duplication is quite common. While it makes the write operations more complex (due to the need to fan out the data), it makes read operations really simple, and extremely scalable.

    To learn more about dealing with updates to duplicated data, see How to write denormalized data in Firebase.

I'd also recommend:

Upvotes: 1

Related Questions