且构网

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

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

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

建议您使用其他数据结构:

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现在只能自动出现一次.实际上,我们已将数据建模为 set 而不是使用数组.
  • 添加项目现在与ref.child("uUids").child("user3").setValue(true)
  • 一样容易
  • 您现在可以检查安全规则中是否存在uid.
  • each uid can now automatically only appear once. We've essentially modeled our data as a set, instead of using an array.
  • adding an item is now as easy as ref.child("uUids").child("user3").setValue(true)
  • you can now check if a uid exists in your security rules.

我已经开始对自己重复:只要您发现自己在做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 
}