2

I get all the games from a firebase collection. This gamescollection is looking like following:

{
    zgaHRO2yW6lafg1ubz4y : { // This is a game
        createdOn: Timestamp,
        finished: false,
        game: "TNhII8jDU23GUZyyqH5X",
        players: {
            NJ2U5MwVAIww6TWkHMv2: true,
            lfNFlKnsbuUJGwINcJ4RMXbNVfs1: true
        },
        startedBy: "lfNFlKnsbuUJGwINcJ4RMXbNVfs1"
    },
    QSkjMQS1232ezklmqKSDJoi : { // This is a game
        createdOn: Timestamp,
        finished: false,
        game: "TNhII8jDU23GUZyyqH5X",
        players: {
            AQSDNJ2U5MwVAIwWkHMv2: true,
            lfNFlKnsbuUJGwINcJ4RMXbNVfs1: true
        },
        startedBy: "lfNFlKnsbuUJGwINcJ4RMXbNVfs1"
    }
}    

To get all the games, I perform the following action:

const gamesCollection = db.collection('games')
firebase.gamesCollection.where('finished', '==', false).orderBy('createdOn', 'desc').onSnapshot(querySnapshot => {
    querySnapshot.forEach(doc => {
        const games = doc.data()
    })
})

This works nice: I get all the games that are not finished yet... But now I want to "query" them like such:

  1. Get all the games where player lfNFlKnsbuUJGwINcJ4RMXbNVfs1 is involved.
  2. Get all the games where player lfNFlKnsbuUJGwINcJ4RMXbNVfs1 OR player NJ2U5MwVAIww6TWkHMv2 is involed

Can't seem to figure out how it's done...

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
user1141796
  • 304
  • 1
  • 2
  • 12

1 Answers1

0

Since you stored the players in a map, for the first case you can query for the players object property corresponding to the playerId, as follows:

  const playerIdToCheck = 'AQSDNJ2U5MwVAIwWkHMv2'
  const gamesCollection = db.collection('games')

  gamesCollection
    .where('players.' + playerIdToCheck, '==', true)
    .onSnapshot(querySnapshot => {
      querySnapshot.forEach(doc => {
        const games = doc.data()
        console.log(doc.id, ' => ', games);
      });
    });`

For the second case (the 'OR' query), actually it is not possible to execute OR queries as such in Firestore: you will therefore have to execute the two queries (i.e. one for lfNFlKnsbuUJGwINcJ4RMXbNVfs1 and one for NJ2U5MwVAIww6TWkHMv2) and merge them in your front-end.

You can red more about OR queries and possible work around here: Implementing OR in firestore query - Firebase firestore or here https://stackoverflow.com/search?tab=relevance&q=firestore%20OR%20query

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121