1
votes

I'm currently learning Firebase/NoSQL database modeling. I just ended watching the Firebase for SQL developers, but I still have few doubts.

Let's say I'm creating Instagram-styled app where users could share their photos and each user could like each photo.

So I would like to achieve two things: 1. Know which user has liked which photo. (So only one like per user for photo) 2. How many likes each photo has.

My current database looks like this:

{
  "images": {
    "100": {
      "imageUrl": "../../image.png",
    },
    "101": {
      "imageUrl": "../../image.png",
    }
  },
  "users": {
    "200": {
      "name": "user1"
    },
    "201": {
      "name": "user2"
    }
  },
  "likes": {
    "100": 1,
    "101": 2
  },
  "likesPerUser": {
    "200": {
      "100": "true"
    },
    "201": {
      "100": "true",
      "101": "true"
    }
  }
  "imagesPerUser": {
    "200": {
        "101": "true"
    },
    "201": {
        "100": "true"
    }
}

My question is related to the counter, that counts how many likes each photo has. Would the best practice be that I have them as their own "root"-object (current model) OR to create key-value pair for "likes" under the photo (and maybe do the same for authorID)?

1

1 Answers

2
votes

This Firebase Sample recommends having the counter(likes_count) under each post. And also having a node(likes) with a list/lookup . Like this:

"images": {
    "100": {
      "imageUrl": "../../image.png",
      "likes_count":2,
      "likes":{
        "200":true,
        "201":true
      }
    },
    "101": {
      "imageUrl": "../../image.png",
      "likes_count":1,
      "likes":{
        "201":true
      }
    }
}

This way you'll ensure only one like per user, because keys must be unique under a Firebase Realtime Database node, and the user ids are used as keys under the likes_count node. You can also know which users liked the photo because their uids are there. And obviously, you can see how many likes a photo has by accessing the counter.