user1164937
user1164937

Reputation: 2117

Firebase data structure for sorting referenced entities

How should I design the structure so that users can view their subscribed channels' videos (e.g., youtube)?

The following is what I have in mind, but I'm uncertain about fetching just a few channels' videos at a time, from newest to oldest. With this, the user has to fetch all of the videos for each channel, and sort them on the client side. Is this even scalable?

{
  "subscriptions": {
    "user1": {
      "channel1": true,
      "channel3": true,
      "channel14": true
    }
  }
}

Upvotes: 0

Views: 38

Answers (1)

Alan K.
Alan K.

Reputation: 227

In this case, I would recommend adding a "userVideos" index reference (not to be confused with the index I'm about to mention) where you keep a list of all videos the user is subscribed to, with an .indexOn rule on the ``userVideos/{userID}/{videoID}.date` field.

Whenever a channel releases a new video, you should add the video to all of the channel's subscriber's video lists. When a user subscribes to a new channel, simply add all of the channel's videos to the user's videos.

You can read more about how denormalizing/flattening your data structures like this can be effective in Firebase's data structures guide.

- userSubscriptions
  "user1"
    "channel1" : true
    "channel2" : true
    "channel4" : true
- subscriptionUsers
  "channel1"
    "user1" : true
    "user2" : true
    ...
  "channel2"
     "user1" : true
  ...
- userVideos
  "user1"
    "video1"
      "date" : <date>
    "video2" : true
      "date" : <date>

Upvotes: 2

Related Questions