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:
I want to get a random user, that is all.
Any ideas?
Solution 1:
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.
Solution 2:
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