Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I randomly get same data on Firebase?

I have user table and this code.

getOnline code and connected button

var onlineStatus = firebase.database().ref("users/" + firebase.auth().currentUser.uid + "/online");
onlineStatus.set(1);  

and

var dbUser = firebase.database();
var refUser = dbUser.ref("users");


refUser.orderByChild("online").equalTo(1).on("value", function(Data){
    console.log(Data.val(), Data.key);
});

I can already see online=1 users, but I want to randomly get 1 user who has the online = 1.

How can I do this?

Update

I want to build randomly chat. people will match according to the criteria. like Tinder App. Think about it, there is a page and button. When the user presses the button, it will match any online user. and chatting.

firebase users;

users
     VIkvYAtLHxNqAwd722oKenriM7PJz2
        email: "[email protected]"
        online: 1 
        profile_picture:"https://scontent.xx.fbcdn.net" 
        username: "John Snow"

     DIkvYAtLHxNqAwd722oKenriM7PJz2
        email: "[email protected]"
        online: 1 
        profile_picture:"https://scontent.xx.fbcdn.net" 
        username: "Jane Snow"
like image 804
cnsvnc Avatar asked Feb 04 '18 23:02

cnsvnc


People also ask

Can Firebase get hacked?

New research from Comparitech suggests that common misconfigurations of Google Firebase databases are exposing sensitive information, including passwords, telephone numbers, and chat messages, to anyone who wants to look.

Can we retrieve data from Firebase?

Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.

Does Firebase automatically scale?

Lastly, it'll scale massively and automatically. Firebase Functions will just do it automatically for you based on the traffic you receive and at an incredibly low cost.

How do I get random documents from firestore?

An easy way to grab random documents is get all the posts keys into an array ( docA , docB , docC , docD ) then shuffle the array and grab the first three entries, so then the shuffle might return something like docB , docD , docA . Okay thats a good idea!


1 Answers

You can use the Math.random() function to get a random number (let's call it n) and then get the nth user online:

refUser.orderByChild("online").equalTo(1).on("value", function(Data){
    console.log(Data.val(), Data.key);
    var totalOnline = Data.numChildren(); //get number of online users
    var randomNr = Math.random() * totalOnline;
    var userIndex = parseInt(randomNr, 10); //parse the random number from double to integer
    var currentIndex = 0;
    Data.forEach(function(snap){
        if(currentIndex==userIndex){
            var randomUser = snap.val();
            //Do something with your random user
            break;
        }
        currentIndex++;
    });
});

Also note that if you have a huge app with thousands of users, you might want to limit the query to 50 users to improve the app's performance:

refUser.orderByChild("online").equalTo(1).limitToFirst(50)

Update: To exclude your own user you can check if the random user is you. And if it is, go to the next one:

        if(currentIndex>=userIndex && snap.key != firebase.auth().currentUser.uid){
            var randomUser = snap.val();
            //Do something with your random user
            break;
        }

Update 2: I've discovered that you can't use break on forEach loop. So you can solve that using the solution provided here (use a BreakException):

refUser.orderByChild("online").equalTo(1).on("value", function(Data){
    console.log(Data.val(), Data.key);
    var totalOnline = Data.numChildren(); //get number of online users
    var randomNr = Math.random() * totalOnline;
    var userIndex = parseInt(randomNr, 10); //parse the random number from double to integer
    var currentIndex = 0;
    var BreakException = {};
    try
    {
        Data.forEach(function(snap){
            if(currentIndex==userIndex){
                var randomUser = snap.val();
                //Do something with your random user
                throw BreakException;
            }
            currentIndex++;
        });
    }
    catch(e){
        if(e!== BreakException) throw e;
    }
});
like image 51
Rosário Pereira Fernandes Avatar answered Sep 20 '22 16:09

Rosário Pereira Fernandes