在Firebase结构数据部分中,它显示了如何在许多用户组情况下构造数据。但是,为什么他们在两侧都使用“ referece”:true而不是使用简单的数组od id。
就像,两种方式都可以使用它:
具有组数组的用户
"groups" : [ "groupId1", "groupId2", ... ]
用户拥有
"groups": {
"groupId1" : true,
"groupId2" : true,
..
}
他们做了第二种方式。是什么原因呢?
某些视频在Google I / O 2016上对此有所告知。但是,我不记得了。
数据结构示例:
// 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建议不要在其数据库中使用数组。在此不再重复原因,我将带您参考Firebase中有关数组的经典博客文章。
让我们看一个可以从示例中轻松看到的简单原因。由于JavaScript中的Firebase数组只是具有连续整数键的关联对象,因此您的第一个示例存储为:
"groups" : {
0: "groupId1",
1: "groupId2"
]
要检测此用户是否在中groupId2
,您必须扫描数组中的所有值。当只有两个值时,这可能还不错。但是随着您拥有更多的价值,它很快就会变慢。您也将无法查询或保护此数据,因为Firebase查询或其安全规则均不支持contains()运算符。
现在看一下替代数据结构:
"groups": {
"groupId1" : true,
"groupId2" : true
}
在此结构中,您可以groupId2
通过仅检查一个位置来查看用户是否在其中:/groups/groupId2
。如果密钥存在,则用户是的成员groupId2
。在这种情况下,实际值并不重要,我们仅将其true
用作标记值(因为Firebase将在没有值的情况下删除路径)。
这也可以更好地与查询和安全规则一起使用,因为您现在“只是”需要一个exist()运算符。
要深入了解这种类型的建模,我强烈建议您参阅有关NoSQL数据建模的文章。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句