0

I'm building a solution where I will need to add attributes such as color, type on my products. The products will be able to have more than one color.

So my question is, should I structure my data attributes as arrays in firebase, or objects, or is there an other way?

I would like to filter my products with .eQualTo (or if there is a better way) https://firebase.google.com/docs/reference/js/firebase.database.Query#equalTo

Example 1)

{
name: "My red n' white product",
color: ["white", "red"]
}

Example 2)

{
name: "My red n' white product",
color: {red: true, white: true}
},
{
name: "My blue product",
color: {blue : true}
}

Example 3) ?

Salmin Skenderovic
  • 1,750
  • 9
  • 22

1 Answers1

2

A few things to realized here:

  • Whenever you feel the need to store an array, but then want to do a contains() operation on it: you are probably looking to store a set instead. See my previous answer here for more details: Setting arrays in Firebase using Firebase console

  • Even when you store the colors as a set, you will end up with queries like: ref.orderByChild('color/blue').equalTo(true). While this query works, it requires that you have indexes defined for ['color/blue', 'color/red', 'color/white']. As soon as your categories/colors are dynamic, this won't be possible since you can't programmatically add indexes.

The more idiomatic way to model this data is to "follow the use-case". You want to get a list of items for a specific category/color. So in that case, store a list of items for each color:

itemsByColor: {
  red: {
    keyOfRedAndWhiteProduct: true
  },
  white: {
    keyOfRedAndWhiteProduct: true
  },
  blue: {
    keyOfBlueProduct: true
  }
}

Now you can easily look up the list of item keys and then load them.

I highly recommend also reading the Firebase guide on structuring data, specifically the section on modeling data that scales. And this article on NoSQL data modeling is mandatory reading for anyone making the transition to NoSQL database.

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807