【问题标题】:Updating firebase database (iOS, swift) with multiple fields without overriding existing data使用多个字段更新 firebase 数据库(iOS、swift)而不覆盖现有数据
【发布时间】:2017-09-23 15:03:28
【问题描述】:

已通过参考更新单个字段而不是多个字段来回答此问题。

当用户在我的应用中注册时,我会向 firebase 数据库写入字段列表。 firebase 数据库的根是 users,每个用户节点都是一个指定的唯一用户名。

-users
     -username  
        "name"
        "title"
        "date of birth"
        "location"
        "about"
        "height"

在 UpdateDetailsController 中是一个用户更新页面,他们可以在其中更新其中一些字段:

 let key = model.ref.child("users").child(currentLoggedInUser).key

     let post = [
                        "name": name.text!,
                        "title": title.text!,
                        "about": about.text! ]
            let childUpdates = ["\(key)": post]

            model.ref.updateChildValues(childUpdates)

虽然用户名保持不变,但使用 ref.updateChildValues(childUpdates) 会覆盖整个节点,因此它看起来像:

 -users
         -username  
            "name"
            "title"
            "about"

建议将不胜感激!

谢谢。

【问题讨论】:

  • 它将覆盖您在字典中尝试保存的所有内容...您是说(location, height, about) 也会更新吗?
  • @Lamar 我认为 OP 已经知道这一点,因此他寻求帮助
  • 您对model.ref 的使用似乎不一致。获取用户名(密钥)时,使用model.ref.child("users")。那么更新不应该是model.ref.child("users").updateChildValues(childUpdates)吗?
  • 嗨。感谢回复。在注册时,用户名节点下有 6 个字段......然后当用户进行更新时,这 6 个字段被覆盖,因此节点下只有 3 个字段:名称、标题和关于。
  • 我理解您认为您看到的意外结果。您正在使用正确的更新方法,如example in the documentation 所示。我的评论是:您发布的代码是否真的在更新位置/users/$username/?看起来它正在更新 /$username。

标签: swift firebase


【解决方案1】:

试试:

model.ref.child(key).updateChildValues(post)

【讨论】:

  • 太容易了。谢谢!您介意解释一下该行与此行之间的区别吗: let childUpdates = ["(key)": post], model.ref.updateChildValues(childUpdates) 这显然不正确。
  • 长话短说,您基本上是在更新用户节点而不是用户名节点。我有一种感觉,如果您想保持当前的流量,model.ref.child("users").updateChildValues(childUpdates) 也可以工作?
猜你喜欢
  • 2020-12-03
  • 1970-01-01
  • 2019-04-28
  • 2023-03-18
  • 2022-01-08
  • 1970-01-01
  • 2018-03-06
  • 2020-05-12
  • 2013-06-29
相关资源
最近更新 更多