Pick random value from firebase snapshot

前端 未结 2 1271
自闭症患者
自闭症患者 2021-01-05 23:09

I\'m using firebase\'s foreach to get each child in a tree from this url

Objective, when the page loads grab a random item from firebase and show it

data str

2条回答
  •  鱼传尺愫
    2021-01-06 00:05

    One way to implement this is to store an additional child attribute with each element of your list that will take on a random value. Let's call the name of this attribute "randomVal".

    To pick your random entry you would use orderByChild("randomVal") and then limit the query to returning exactly one entry. Immediately upon fetching this entry, you would write a new random value into the "randomVal" element.

    Beyond the additional bookkeeping work, the biggest downside of this approach is that it requires a write to the database every time you want to select a random element. I'm new to firebase, so I don't know how significant this drawback is.

    Also, make sure to index this part of the database on "randomVal" to improve the query performance.

提交回复
热议问题