Pick random record from Firebase with AngularFire

主宰稳场 提交于 2019-12-08 17:45:30

问题


Is there any way to get random record from firebase like this:

{
  "-JbmopNnshefBT2nS2S7" : {
    "dislike" : 0,
    "like" : 0,
    "post" : "First post."
  },
  "-JbmoudijnJjDBSXNQ8_" : {
    "dislike" : 0,
    "like" : 0,
    "post" : "Second post."
  }
}

I used this code to solve the problem, but it download all records, so if DB would be bigger, my app will work very slow:

HTML code:

    <div ng-controller="RandomCtrl">{{RandomPost.post}}</div>

JS code:

var app=angular.module('App', ['firebase']);

app.controller('RandomCtrl', function($scope, $firebase){
    var ref = new Firebase("https://ind.firebaseio.com/");
    var sync=$firebase(ref);

    $scope.messages = sync.$asArray();

    $scope.GetRandomPost=function(){
        return $scope.RandomPost=$scope.messages[Math.floor(Math.random()*$scope.messages.length)];
    };

    $scope.GetRandomPost();    

});

回答1:


You can use startAt with your own incremental index. For example, suppose you have index (0 to n) in your records.

Do this query: orderByChild("index").startAt(rint).limitToFirst(1);

See the code snippit:

var rint = Math.floor((Math.random() * 10)) // you have 10 records
var query = ref.orderByChild("index").startAt(rint).limitToFirst(1);

var results = $firebaseArray(query);
results.$loaded(
  function(x) {
    // let's get one
    $scope.oneResult = x[0];
  }, function(error) {
    console.error("Error:", error);
  });
};



回答2:


You can work with an object that contains all keys to solve the issue with large DBs, regarding picking up a random key I think you are good the way you are doing it.

Another way to do I guess is using incremental keys as @lombausch said, then you can use a combination of key() method to get the last key added and then get a random based on the min, max values.

Here is the anti-pattern to save incremental/numeric keys: https://www.firebase.com/docs/web/guide/saving-data.html#section-push

key() method reference: https://www.firebase.com/docs/web/api/firebase/key.html



来源:https://stackoverflow.com/questions/27178393/pick-random-record-from-firebase-with-angularfire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!