Reputation: 724
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"
Upvotes: 11
Views: 976
Reputation: 11344
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;
}
});
Upvotes: 7