Firebase database sort by deeper child

后端 未结 2 1751
离开以前
离开以前 2021-01-25 19:49

Considering the following structure of the Firebase database:

  • root
    • game1
      • $playerUidA
        • score: 50
      • $playerUidB
2条回答
  •  青春惊慌失措
    2021-01-25 20:13

    If you want all the games sorted by the player score all you need to do is to work with your .indexOn rule.

    {
      "rules": {
        "$gameId": {
          ".indexOn": "score",
          "$playerUid": {
            ...  
          }
        }
      }
    }
    

    This will keep your data sorted in the database so when you retrieve it you will have all the data ready. But keep in mind that if you want to retrieve all the games and all the players it means you will be fetching the whole database. So you should look at the needs of your application and maybe rethink the structure.

    Something that could help when scaling is to iterate over the games and retrieve a limited amount of users with firebase.database().ref(gameId).limitToLast(10).

    Update

    For your example you will have all the games with the following request:

    firebase.database().ref().once('value', snap => {
        //prints all players for each game sorted ascending.
        snap.forEach(game => {
            game.forEach(player => {
                console.log(player.val());
            });
        });
    });
    

提交回复
热议问题