Get random item from Firebase

后端 未结 4 786
伪装坚强ぢ
伪装坚强ぢ 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.

    0 讨论(0)
  • 2020-12-01 11:56

    I have been looking for the same function, now I guess it can be done with the new released Cloud Firestore, but I'm looking for a simple solution.

    btw. the neat feature of limitToFirst + limitToLast does not work, at least not in javascript (web).

    The best I can come up with (if the key index "time-random" is not enough) are:

    If you only need the data random once (my situation, a deck of random cards):

    add a value with Math.random() and orderByChild() on that number, remove keys or use startAt() with the last used key as parameter.

    var ref = firebase.database().ref('companies/01/users').push();
    var randomValue = Math.random();
    ref.update({ ..., 'r': randomValue });
    
    ...
    
    var ref = firebase.database().ref('companies/01/users')
    ref.orderByChild('r').limitToFirst(1).once('value').then(function(snapshot) {
      var data = snapshot.val()
      ...
      snapshot.remove()
    });
    

    If the data should be used the get a random element many times a known index is needed.

    a known numbered index can be added

    var ref = firebase.database().ref('companies/01/users').push();
    ref.update({ ..., 'r': '0001' });
    
    ...
    
    var ref = firebase.database().ref('companies/01/users')
    ref.orderByChild('r').limitToLast(1).once('value').then(function(snapshot) {
      var totalIndex = Object.values(snapshot.val())[0].r;
    });
    var randomValue = Math.floor(Math.random() * totalIndex);
    ref.orderByChild('r').equalTo(randomValue).once('value').then(function(snapshot) {
      var data = snapshot.val()
    });
    
    0 讨论(0)
  • 2020-12-01 12:09

    First you have retrieve all the userid from the firebase.

    Then declare an array that stores all the userid in it. Below shows on how to store the userId.

    var arr = new Array();
    // or var arr = [];
    arr.push('user001');
    arr.push('user002');
    

    Next you have to select randomly from one of the userId.

    var item = arr[Math.floor(Math.random()*arr.length)];
    // item is randomly picked userId
    

    I'm sorry because i didn't completely show you on how the implementation works as I don't use javascript much.

    Basically this is how the logic works. I hope it helps you :D

    0 讨论(0)
  • 2020-12-01 12:10

    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

    0 讨论(0)
提交回复
热议问题