Reputation: 9230
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
Reputation: 600006
There are two main options
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