Firebase: How to structure data for the most shared posts in the last n days?

冷暖自知 提交于 2020-01-05 04:24:31

问题


Let's assume there is a blog and you would like to list the most liked or shared posts for today, the last 7 days and the last 30 days.

The solution for today is rather easy:

-mostSharedPostsForToday
   -2018-10-08
       -$postId
           -numberOfShares

Then the query would observe mostSharedPostsForToday/2018-10-08 for today's most shared posts ordered by child numberOfShares.

But how to structure the data for the most shared posts in the past n days?

One solution I can think of is to write a cloud function that populates the node mostSharedPostsForThePastNDays on a daily basis. But it seems cumbersome to me. Isn't there a more efficient way?

Edit: As pointed out in the comments of the 1st answer pagination should be supported to save traffic.


回答1:


I recomand you to use another approach. In stead of using the date as your node, remove that node and add a TIMESTAMP for each post like this:

-mostSharedPostsForToday
   -$postId
       - TIMESTAMP: 2018-10-08
       - numberOfShares: 10

To know how many shared you have in a single day, you need to use the following code:

rootRef.child("mostSharedPostsForToday").child(postId).orderByChild("TIMESTAMP").equalsTo("2018-10-08");

And if you want an interval please use the following code:

rootRef.child("mostSharedPostsForToday").child(postId).orderByChild("TIMESTAMP").startAt("2018-10-08").endAt("2018-10-15");

Hope it helps.



来源:https://stackoverflow.com/questions/45616271/firebase-how-to-structure-data-for-the-most-shared-posts-in-the-last-n-days

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!