添加子对象时Firebase,其他子对象被删除

问题描述 投票:0回答:1

我正在尝试将一个孩子添加到名为“ 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])

火力地堡:

“

swift firebase firebase-realtime-database
1个回答
0
投票

当您在子节点上调用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. 对单独的setValueusername属性使用单独的url调用:

    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调用,执行multi-location updatedocs)。

© www.soinside.com 2019 - 2024. All rights reserved.