Nesting stars in Firebase Database

2019-09-06 10:09发布

I find Firebase Database sample very helpful, but I noticed something which worries me a little bit.

I mean in this example user can give star to the post, something like "Like it" on Facebook. In provided sample they nested stars into post, so we have sample object like this:

"post_id" : {
       "author": "username",
       "body": "Some content",
       "starCount": 1
       "stars" : {
              "user_id_who_gave_star" : "true"
       }
      "title": "Some title",
      "uid": "author_id"
}

Such solution has many advantages, like e.g. we can check if have already gave star and hide or change icon, or we can one transaction to change "starCount" and add next value to "stars".

But the problem is when we have big application and 1000 users gave star, so everytime when we download post data we download 1000 userIds which may be not best solution.

Question

My question is, what is best approach for such applications and have someone tested how Firebase works in this situation?

1条回答
闹够了就滚
2楼-- · 2019-09-06 10:38

firebaser here

When writing the examples for our documentation, we always have to balance the need for having enough context, keeping the example small enough , and following our own best practices.

This is indeed one of the cases where we violate one of our own best practices "not nesting data". As you said: this means that a user downloading a post, gets all the UIDs of users that liked that post.

As the usage of the application scales, that may become a concern. If that is the case for your app, you should model the "users who upvoted a post" as a separate top-level node:

"posts": {
    "post_id" : {
       "author": "username",
       "body": "Some content",
       "starCount": 1
      "title": "Some title",
      "uid": "author_id"
    }
},
"upvotes": {
    "post_id" : {
        "user_id_who_gave_star" : "true"
    }
}
查看更多
登录 后发表回答