从Firebase获取随机物品 [英] Get random item from Firebase
问题描述
我搜索了它,但是所有答案都还很老,所以也许有更好的方法.我正在尝试从Firebase数据库中获取一个随机项目,如下所示:
I searched for it, but all the answers are pretty old so maybe there is a better way. I'm trying to get a random item from a Firebase DB which looks like this:
我想得到一个随机用户,仅此而已.
I want to get a random user, that is all.
有什么想法吗?
推荐答案
如果知道有多少用户,则可以执行以下操作:
If you know how many users there are, you can do this:
const numberOfUsers = 15;
const randomIndex = Math.floor(Math.random() * numberOfUsers);
var ref = firebase.database().ref('companies/01/users');
ref.limitToFirst(randomIndex).limitToLast(1).once('value').then(snapshot =>
{
var user = snapshot.val();
// do something with the user data
});
但是,如果您不知道有多少个孩子(或在其他位置存储了孩子列表),则没有直接的方法来解决此问题,而无需先在树中接收所有孩子.参见
However, if you don't know how many children there are (or have a children list stored somewhere else), there is no direct way to solve this problem without first receiving all children in the tree. See In Firebase, is there a way to get the number of children of a node without loading all the node data? for more info.
这篇关于从Firebase获取随机物品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!