Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random item from 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:

enter image description here

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

Any ideas?

like image 245
Ace Avatar asked Jul 17 '17 13:07

Ace


2 Answers

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.

like image 165
Elmar Jansen Avatar answered Nov 15 '22 16:11

Elmar Jansen


I had to resolve the same problem, I added a random number from 0 to 1 to all records to finally filter by startAt and limitToFirst to 1.

Example: https://your-project-qwert.firebaseio.com/example.json?orderBy="random"&limitToFirst=1&startAt=0.84

like image 40
Guillermo Jose Aiquel Avatar answered Nov 15 '22 17:11

Guillermo Jose Aiquel