Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  194] [ 2]  / answers: 1 / hits: 21297  / 7 Years ago, mon, july 17, 2017, 12:00:00

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:


enter


I want to get a random user, that is all.


Any ideas?


More From » firebase

 Answers
30

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

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.


[#57057] Friday, July 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carolyn

Total Points: 618
Total Questions: 119
Total Answers: 86

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;