从 Firebase 获取随机项目 [英] Get random item from Firebase

查看:23
本文介绍了从 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.

有什么想法吗?

推荐答案

似乎这个解决方案不起作用,因为limitToFirst"和limitToLast"不允许一起使用.作为参考,这是建议的(不起作用)解决方案,假设您知道用户数量:

seems that this solution does not work, as "limitToFirst" and "limitToLast" are not allowed to be used together. For reference, this was the proposed (not working) solution, assuming you know the number of users:

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
});

如果您不知道有多少个孩子(或者在其他地方存储了一个孩子列表),那么如果不首先接收树中的所有孩子,就没有直接的方法来解决这个问题.见 在 Firebase 中,有没有办法在不加载所有节点数据的情况下获取节点的子节点数量? 了解更多信息.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆