在最近的博客文章 denormalising data 中,它建议在每个用户下面记录所有用户的评论,如下所示:
comments: {
comment1: true,
comment2: true
}
为什么这不是这样的列表:
comments: [
"comment1",
"comment2",
]
有什么优点?有什么区别吗?当我这样做时,您将如何为分布式应用程序的这些评论生成唯一的引用?我想象通过一个列表,我只需将它们推到末尾并让数组处理索引。
最佳答案
Firebase 只存储对象。 JS 客户端使用索引作为键将数组转换为对象。因此,例如,如果您使用 set
存储以下数组:
comments: [
"comment1",
"comment2"
]
在 Forge(图形调试器)中,它将显示为:
comments:
0: comment1
1: comment2
鉴于此,直接将评论 ID 存储为键的优点是您可以直接在安全规则中引用它,例如使用如下表达式:
root.child('comments').hasChild($comment)
为了生成这些评论的唯一引用,请使用 push
( https://www.firebase.com/docs/managing-lists.html ):
var commentsRef = new Firebase("https://<example>.firebaseio.com/comments");
var id = commentsRef.push({content: "Hello world!", author: "Alice"});
console.log(id); // Unique identifier for the comment just added.
关于firebase - 为什么在对数据进行非规范化时使用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16072494/