Reputation: 23161
I'm trying to query my Firebase Realtime Database to find all games a user belongs to.
I have a list of games
, each game has a property of players
. Each child of players
has a key of $uid
, and within that {key: $uid, name: "joe"}
Is it possible to get all games this way? Or do I need to start keeping another index of players_games/$uid/$game
?
I've tried firebase.database().ref('games').orderByChild('players').equalTo(token.uid)
, but this yields null
It looks like database.ref('games').orderByChild('players/${token.uid}')
works, but then I'd need to give .read
access to all of games
, or do this server-side.
Upvotes: 1
Views: 661
Reputation: 598728
Your current data structure makes it easy to find all the users for a specific game. It does not however make it easy to find all the games for a specific user. To allow that, you'll want to add an addition data structure that inverts the information.
So that'd look something like this:
player_games: {
"XDYNyN8il6TDsM4LuttwDzNuytj1": {
"-M5vf...U5zK": true
},
"NxH14...mxY2": {
"-M5vf...U5zK": true
}
}
Also see:
I recommend you also study the Firebase documentation on structuring your database, specifically the section on avoiding nested data. By mixing entity types as you currently do, you'll likely run into problems with security, and scalability.
The most idiomatic way to model your many-to-many relationship in the Firebase database is with four top-level lists:
players: {
$playerId: { ... }
}
games: {
$gameId: { ... }
}
player_games: {
$playerId: {
$gameId: true
}
}
game_players: {
$gameId: {
$playerId: true
}
}
Also see:
Upvotes: 3