我有用户表和这段代码。
getOnline代码和连接按钮
var onlineStatus = firebase.database().ref("users/" + firebase.auth().currentUser.uid + "/online");
onlineStatus.set(1);
和
var dbUser = firebase.database();
var refUser = dbUser.ref("users");
refUser.orderByChild("online").equalTo(1).on("value", function(Data){
console.log(Data.val(), Data.key);
});
我已经可以看到 online=1 的用户,但我想随机得到 1 个 online=1 的用户。
我该怎么做?
更新
我想建立随机聊天。人们将根据标准进行匹配。像火种应用程序。想一想,有一个页面和一个按钮。当用户按下按钮时,它将匹配任何在线用户。和聊天。
Firebase 用户;
users
VIkvYAtLHxNqAwd722oKenriM7PJz2
email: "mail@hotmail.com"
online: 1
profile_picture:"https://scontent.xx.fbcdn.net"
username: "John Snow"
DIkvYAtLHxNqAwd722oKenriM7PJz2
email: "mail2@hotmail.com"
online: 1
profile_picture:"https://scontent.xx.fbcdn.net"
username: "Jane Snow"
最佳答案
您可以使用 Math.random()函数获取一个随机数(我们称它为 n),然后让第 n 用户在线:
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++;
});
});
另请注意,如果您有一个拥有数千名用户的大型应用,您可能希望将查询限制为 50 个用户以提高应用的性能:
refUser.orderByChild("online").equalTo(1).limitToFirst(50)
更新:要排除您自己的用户,您可以检查随机用户是否是您。如果是,请转到下一个:
if(currentIndex>=userIndex && snap.key != firebase.auth().currentUser.uid){
var randomUser = snap.val();
//Do something with your random user
break;
}
更新 2: 我发现您不能在 forEach
循环中使用 break
。因此,您可以使用提供的解决方案解决该问题 here (使用 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;
}
});
关于javascript - 我如何在 Firebase 上随机获取相同的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48614157/