Get random item from Firebase

后端 未结 4 812
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 11:18

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:

4条回答
  •  误落风尘
    2020-12-01 11:56

    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.

提交回复
热议问题