user3258741
user3258741

Reputation: 93

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

});

Upvotes: 7

Views: 2428

Answers (2)

Sung Kim
Sung Kim

Reputation: 8536

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

Upvotes: 2

Everton Yoshitani
Everton Yoshitani

Reputation: 946

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

Upvotes: 0

Related Questions