【问题标题】:React+Firebase: How to add item to list data into firebase realtime databaseReact+Firebase:如何将项目添加到 Firebase 实时数据库中
【发布时间】:2019-11-11 00:50:28
【问题描述】:

我正在使用 react 和 firebase 实时数据库。我想为每个用户创建一个列表。稍后在存储中查找文件的 id 列表。在这种情况下,生成 id 并将其添加到数据库中的最佳方法是什么? (不是数据列表,数据库中存储的数据就是列表)

所以我想到了两种方法。我会写成伪代码

//Method 1
//get id list
receivedList = getKeyListFromDB()
//generate ID
newID = generateID()
// append new id
receivedList.append(newID)
//set value with updated list
updateDB(receivedList)

//Method 2
// Using the list provided by the firebase
newRef = firebase.database().ref().child('pathToList').push()
newRef.set({
      key: newRef.key
    })

我打算使用方法 1,但找不到生成 id 的方法。并且检索列表以更新它似乎效率低下。所以我试图找到另一种方法。但是我找不到这样做的好方法。

将值添加到数据库中的解决方案

我已经用事务方法解决了。但是,如果有办法通过使用push 来解决,请回答。

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案1】:

    Firebase 有一个内置的push() 操作来将子节点添加到列表中的原因有很多。事实上,你已经在你的问题中听过其中一个:

    检索列表以更新它似乎效率低下

    其他原因是推送 ID 将在您的应用离线时工作,并且它们可以更好地跨多个用户扩展。

    如果您想详细了解为什么应该使用push(),请阅读Best Practices: Arrays in Firebase

    【讨论】:

      【解决方案2】:

      首先,您可以使用以下代码生成唯一密钥

      const newID = firebase.database.ref().push().key
      

      根据this answer,每当您在数据库引用上使用推送时,都会使用包含服务器时间戳的唯一键生成一个新数据节点。这些键看起来像 -KiGh_31GA20KabpZBfa。

      由于时间戳,您可以确保给定的键是唯一的,而无需检查数据库中的其他键。

      其次,您可以使用transaction将项目添加到数据库中的列表中。

      const newID = firebase.database.ref().push().key
      //user is user object from firebase auth module
      const newDatabaseRouteRef = firebase.database.ref().child('users/' + user.uid + '/ids')
      // if null, create a new list with id, if not add newID to list
      newDatabaseRouteRef.transaction((currentValue) => {
        return currentValue ? currentValue.push(newID) : [newID]
      })
      

      【讨论】:

        【解决方案3】:

        我正在创建另一个答案,只是为了展示不同类型的解决方案。此解决方案,使用push 比使用transaction 更好。

        // Get a new ref by push
        const newDatabaseRouteRef = firebase.database.ref().child('users/' + user.uid + '/routes').push()
        // Set the value to the key of received ref
        newDatabaseRouteRef.set(newDatabaseRouteRef.key)
        

        这样更好,因为

        1. 事务需要多次往返,而 push() 不需要,从而减少时间。
        2. 根据this article 更安全。

        这实现了相同的结果,因为即使使用列表,当列表保存在 firebase 数据库中时,它也会作为对象存储。 ex) ["a","b","c"] => {0:"a",1:"b",2:"c"}

        【讨论】:

          猜你喜欢
          • 2021-03-24
          • 2017-10-24
          • 1970-01-01
          • 2017-02-10
          • 2021-10-04
          • 2020-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多