Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick random record from Firebase with AngularFire

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

});
like image 943
user3258741 Avatar asked Nov 27 '14 20:11

user3258741


1 Answers

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);
  });
};
like image 136
Sung Kim Avatar answered Nov 13 '22 14:11

Sung Kim