【问题标题】:Firebase nested data using "reference" : true instead of arrayFirebase 使用“reference”嵌套数据:true 而不是数组
【发布时间】:2016-06-23 15:58:51
【问题描述】:

在 firebase structure data 部分,它展示了如何在多对多用户组的情况下构造数据。但是,为什么他们在两边都使用了 "referece":true 而不是使用简单的数组 od ids。

就像,它可以像两种方式一样使用:

  1. 拥有一组组的用户

    "groups" : [ "groupId1", "groupId2", ... ]
    
  2. 用户拥有

    "groups": {
        "groupId1" : true, 
        "groupId2" : true,
        ..
    }
    

他们采用了第二种方式。这是什么原因?

在 2016 年 Google I/O 大会上,一些视频对此进行了说明。但是,我想不起来了。

数据结构示例:

// An index to track Ada's memberships
{
  "users": {
    "alovelace": {
      "name": "Ada Lovelace",
      // Index Ada's groups in her profile
      "groups": {
         // the value here doesn't matter, just that the key exists
         "techpioneers": true,
         "womentechmakers": true
      }
    },
    ...
  },
  "groups": {
    "techpioneers": {
      "name": "Historical Tech Pioneers",
      "members": {
        "alovelace": true,
        "ghopper": true,
        "eclarke": true
      }
    },
    ...
  }
}

【问题讨论】:

    标签: firebase data-structures firebase-realtime-database nosql


    【解决方案1】:

    Firebase 建议在大多数情况下不要在其数据库中使用数组。这里不再重复原因,我给你推荐这个经典的blog post on arrays in Firebase

    让我们看一个简单的原因,您可以从您的示例中轻松看出这一点。由于 JavaScript 中的 Firebase 数组只是具有顺序整数键的关联对象,因此您的第一个示例存储为:

    "groups" : { 
      0: "groupId1", 
      1: "groupId2"
    ]
    

    要检测此用户是否在groupId2 中,您必须扫描数组中的所有值。当只有两个值时,这可能还不错。但是当你有更多的价值时,它很快就会变慢。您也无法查询或保护这些数据,因为 Firebase 查询及其安全规则都不支持 contains() 运算符。

    现在看看另一种数据结构:

    "groups": {
        "groupId1" : true, 
        "groupId2" : true
    }
    

    在这个结构中,您可以通过精确检查一个位置来查看用户是否在groupId2/groups/groupId2。如果该密钥存在,则用户是groupId2 的成员。在这种情况下,实际值并不重要,我们只是使用true 作为标记值(因为如果没有值,Firebase 会删除路径)。

    这也将更好地用于查询和安全规则,因为您现在“只是”需要一个 exists() 运算符。

    如果想深入了解这种类型的建模,我强烈推荐NoSQL data modeling 上的那篇文章。

    【讨论】:

    • 明白了!实际上我在 I/O 2016 看到有人解释 /groups/groupId2 != null,但我完全忘记了用法,找不到那个特定的视频。感谢您的精彩解释!上周我看到了那篇 NoSQL 数据建模文章。在我的阅读清单中!
    猜你喜欢
    • 1970-01-01
    • 2020-03-24
    • 2021-12-20
    • 2017-05-28
    • 1970-01-01
    • 2020-02-12
    • 2019-03-29
    • 1970-01-01
    • 2019-01-14
    相关资源
    最近更新 更多