首页 > 解决方案 > 添加孩子时的Firebase,另一个孩子被删除

问题描述

我正在尝试向名为“users_want_notification”的孩子添加一个孩子。这似乎可行,但是当我尝试将第二个孩子添加到名为“users_want_notification”的孩子中时,第一个孩子将被删除。我怎样才能改变这个,所以第一个孩子不会被删除?

我的代码:

Database.database().reference()
  .child("Notification").child("users").child(username)
  .setValue(["username": username, "url": Foto_url])
Database.database().reference()
  .child("Notification").child("users").child(username)
  .child("users_want_notification").child(Pro_user)
  .setValue(["Pro_user": Pro_user, "toDeviceID": AppDelegate.DEVICEID])

火力基地:

火力基地

标签: swiftfirebasefirebase-realtime-database

解决方案


当您调用setValue子节点时,该节点下的所有现有数据都将替换为您传递给的值setValue。如果我们查看您的第一个电话:

Database.database().reference()
  .child("Notification").child("users").child(username)
  .setValue(["username": username, "url": Foto_url])

这将替换 下的所有现有数据/Notification/users/$username,包括其users_want_notification子节点下的所有数据。由于您随后在 下添加了一个新的子节点users_want_notification,看起来该调用替换了现有的子节点,但实际上它是第一个setValue删除所有数据的调用。你可以通过暂时注释掉第二个调用来测试它,你会看到整个users_want_notification消失了。

您有两个主要选择:

  1. 对个体和属性使用单独setValue的调用:usernameurl

    let userRef = Database.database().reference()
      .child("Notification").child("users").child(username)
    userRef.child("username").setValue(username)
    userRef.child("url").setValue(Foto_url])
    userRef.child("users_want_notification").child(Pro_user)
      .setValue(["Pro_user": Pro_user, "toDeviceID": AppDelegate.DEVICEID])
    

    由于现在所有setValue调用都发生在低于 的级别/Notification/users/$username,因此永远不会替换整个节点。

  2. 对所有数据使用一次updateChildNodes调用,执行多位置更新( docs )。


推荐阅读