Get random item from Firebase

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

    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()
    });
    

提交回复
热议问题