Firebase(Vue)通过(多个)子值获得

时间:2018-12-01 10:14:16

标签: firebase vue.js google-cloud-firestore

我从firebase集合中获得所有游戏。该游戏集合如下所示:

{
    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"
    }
}    

要获取所有游戏,请执行以下操作:

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

这很好用:我得到了所有尚未完成的游戏...但是现在我想像这样“查询”它们:

  1. 获取所有涉及玩家lfNFlKnsbuUJGwINcJ4RMXbNVfs1的游戏。
  2. 获取涉及玩家lfNFlKnsbuUJGwINcJ4RMXbNVfs1或玩家NJ2U5MwVAIww6TWkHMv2的所有游戏

似乎无法弄清楚它是如何完成的...

1 个答案:

答案 0 :(得分:0)

由于您将玩家存储在地图中,因此在第一种情况下,您可以查询与players相对应的playerId对象属性,如下所示:

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

对于第二种情况(“ OR”查询),实际上不可能在Firestore中执行此类OR查询:因此,您将必须执行两个查询(即,对于lfNFlKnsbuUJGwINcJ4RMXbNVfs1另一个用于NJ2U5MwVAIww6TWkHMv2),然后将它们合并到您的前端。

您可以在以下位置对有关OR查询的更多信息进行红色处理:Implementing OR in firestore query - Firebase firestore或此处https://stackoverflow.com/search?tab=relevance&q=firestore%20OR%20query