如何在Firebase上随机获取相同的数据?

时间:2018-02-04 23:46:36

标签: javascript firebase react-native firebase-realtime-database

我有用户表和这段代码。

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

我已经可以看到在线= 1个用户,但我想随机获得1个在线= 1的用户。

我该怎么做?

更新

我想随意聊天。人们会根据标准进行匹配。喜欢Tinder App。想想看,有一个页面和按钮。当用户按下按钮时,它将匹配任何在线用户。和聊天。

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"

1 个答案:

答案 0 :(得分:6)

您可以使用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 :我发现您无法在break循环中使用forEach。所以你可以使用提供的解决方案来解决这个问题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;
    }
});