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();
});
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);
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With