【问题标题】:How do you get an item from Realtime Database where you need to look into a child and check if the array has the id you are looking for如何从需要查看子项并检查数组是否具有您要查找的 id 的实时数据库中获取项目
【发布时间】:2021-12-15 17:02:50
【问题描述】:

通过一个例子更容易解释。

有问题的数据是:

data : { 

cluster1 : { 
id: 123 
things: [153, 525, 743] 
},

cluster2 : { 
id: 124 
things: [113, 547, 124] 
},

}

我们想找到所有包含“547”的集群,这种情况应该返回整个集群2。

我知道如何在 Firestore 中执行此操作,它看起来像这样:

  db.collection("data")
        .where("things", "array-contains", userInput)

但由于某些原因,我不能使用 firestore。

有谁知道在 Firebase 实时数据库中是否有办法做到这一点。

谢谢!

【问题讨论】:

    标签: javascript firebase firebase-realtime-database


    【解决方案1】:

    实时数据库 API 中没有与 Firestore 的 array-contains 等效的功能。您可以获得的最接近的是将数据存储为地图,以true 作为它们的值:

    data : { 
      cluster1 : { 
        id: 123 
        things: {
          "153": true, 
          "525": true,
          "743": true
        } 
      },
      cluster2 : { 
        id: 124 
        things: {
          "113": true, 
          "547": true, 
          "124": true
        } 
      },
    }
    

    现在您可以为things 中的每个属性定义一个索引,然后在查询中使用它:ref.orderByChild("things/113").equalTo(true)


    由于things 数组中的值可能是动态的且未预定义,因此您将无法为它们定义索引。在这种情况下,您需要添加一个反向数据结构,将事物 ID 映射回集群。

    有关这方面的示例,请参阅Firebase query if child of child contains a value

    有关此主题的更多信息,另请参阅:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多