I'm trying to build a leaderboard for my users inside my realtime db.
That's the structure of my db:
_firebase_db_url {
users: {
user1: {
displayName: "name",
...some_other_infos...
games: {
game1: {
lastScore: 123,
timePlayed: 120
},
game2: {
lastScore: 456,
timePlayed: 360
},
...
}
}
},
games: {
0 : {
"id": "game1",
"description": "..."
},
1 : {
"id": "game1",
"description": "..."
},
...
}
What I'm trying to do is making a query on the db to get max 10 player ordered by lastScore on a certain game.
I've tried so far:
db.ref('/users')
.orderByChild(`lastScore`)
.limitToFirst(10)
.get()
.then((val) => console.log(val.val()));
This prints my users but not ordered by game scores
I've also tried to make a loop on all games and then the query on the db:
db.ref('/games')
.get()
.then(
(result) => {
const gamesList = result.val();
const gamesIdsArray = []
Object.values(gamesList)
.forEach(game => {
gamesIdsArray.push(game.id)
})
return gamesIdsArray;
}).then( // Once I got entirely my array filled with the games ID, I proceed
(gamesIdsArray) => {
gamesIdsArray.forEach(gameId => {
db.ref('/users')
.orderByChild(`lastScore`)
.limitToFirst(10)
.get()
.then((val) => console.log(val.val()))
})
}
)
This prints for the number of games all my users not ordered by games. (It prints the users also if them don't have the specific game obj: if I'm looping on game5
the query prints 10 users including users that don't have the filed game5
inside their games
section).
Other tries:
db.ref('/users')
.child('games')
.child(`${req.userId}/games/${gameId}`) //passing the userId inside my https.onRequest() function
.orderByChild(`lastScore`)
.limitToFirst(10)
.get()
.then((val) => console.log(val.val()))
Still nothing useful
db.ref('/users/{userId}/games{gameId}/lastScore')
.orderByChild(`lastScore`)
.limitToFirst(10)
.get()
.then((val) => console.log(val.val()))
Still nothing useful
I've also included in my realtime db rules all the .indexOn
I've tried so far.
Nothing helped.
What am I doing wrong? What should I try? Should I switch to Firestore to keep user data?
[ EDITED ]
I've slightly edited my db set as follows based on Frank's answer:
db {
users: {
"user1": {
name: "name1",
... some other infos
},
"user2": {
name: "name2",
... some other infos
},
...
}
games: {
"game1": {
"user1": {
bestScore: 123
},
"user2": {
bestScore: 234
}
},
"game2": {
"user1": {
bestScore: 765
},
"user2": {
bestScore: 543
}
}
}
}
Query that prints the users but not ordered:
db.ref("games")
.child(gameId) //getting my gameId var from request.data.gameId from my onCall function
.orderByChild("bestScore")
.once('value', (res) => {
console.log(res.val())
return res.val()
})
And still getting the users not ordered