且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将项目添加到 Firebase 数据库中的列表

更新时间:2023-12-05 23:16:04

有关创建可扩展数据的 Firebase 文档 建议您使用不同的数据结构:

The Firebase documentation on creating data that scales proposes that you use a different data structure:

"requests" : {
  "-KSVYZwUQPfyosiyRVdr" : {
    "interests" : { "x": true },
    "live" : true,
    "uIds" : { 
      "user1": true, 
      "user2": true 
    }
  },
  "-KSl1L60g0tW5voyv0VU" : {
    "interests" : { "y": true },
    "live" : true,
    "uIds" : { 
      "user2": true 
    }
  }
}

以下是该数据结构效果更好的一些原因:

Here are a few of the reasons why this data structure works better:

  • 每个 uid 现在只能自动出现一次.我们基本上将数据建模为集合,而不是使用数组.
  • 添加项目现在就像ref.child("uUids").child("user3").setValue(true)
  • 您现在可以检查安全规则中是否存在 uid.

我开始反复提醒自己:每当你发现自己在做 array.contains("xyz") 时,你可能应该使用集合而不是数组. 上面带有 "key": true 的映射是 Firebase 上集合的实现.

I have started re-iterating to myself: whenever you find yourself doing array.contains("xyz"), you should probably be using a set instead of an array. The above mapping with "key": true is an implementation of a set on Firebase.

有些人可能认为数组是一种更有效的数据存储方式,但在 Firebase 的情况下并非如此:

Some people may think arrays are a more efficient way of storing the data, but in the case of Firebase that is not true:

你看到的:

"uIds" : [ "user1", "user2" ]

Firebase 存储的内容:

What Firebase stores:

"uIds" : {
  "0": "user1",
  "1": "user2"
}

所以存储一个集合几乎是一样的:

So storing a set is pretty much the same:

"uIds" : { 
  "user1": true, 
  "user2": true 
}