首页 > 解决方案 > 如何将一个子节点移动到另一个子节点下?

问题描述

我已经研究并尝试了一些关于堆栈溢出的建议,但代码似乎不起作用。我一直在尝试通过复制然后删除节点来移动节点,但最终所有内容都在 firebase 中被删除(原始和复制的帖子)。

目标:在用户点击按钮后,将数据从子“待处理”移动到子“发布”。

我想将Shelly A. 待处理的帖子移到帖子下。

Firebase 数据库:

-pending
  -childByAutoId()
    -name: Shelly A.
    -post: "Haha"

-posts
  -childByAutoId()
    -name: Josh A.
    -post: "funny"

代码

ref = Database.database().reference()

//copying the node from the child "pending" to child "posts"
self.ref.child("pending").child(event.id!).observe(.value, with: { (snapshot) in
                self.ref.child("posts").child(event.id!).setValue(snapshot.value)

            })
        //deleting the original posts
            self.ref.child("pending").child(event.id!).setValue(nil)

看着数据库,我能够复制数据,但一秒钟后,新复制的数据被旧帖子完全删除。有什么帮助吗?

标签: swiftfirebase-realtime-database

解决方案


如果您看到在回滚之前短暂地进行了更改,最常见的情况是因为您有一个拒绝更改的安全规则

在这种情况下,客户端首先触发更改的本地事件,然后将更改发送到服务器。然后,当它从服务器听到更改被拒绝时,它会触发本地事件以再次使状态正确。

因此,在您的情况下,您可以从 中删除节点pending,但不允许在 下添加数据posts


防止这种类型的部分操作的一个好方法是将删除和写入都包含在单个多位置更新操作中。

ref = Database.database().reference()

self.ref.child("pending").child(event.id!).observe(.value, with: { (snapshot) in
    var updates = [
        "posts/\(event.id!)": snapshot.value,
        "pending/\(event.id!)": nil
    ]
    self.ref. updateChildValues(updates)
})

使用此代码,新节点的写入和旧节点的删除都作为一个操作发送到数据库,因此也被您的安全规则接受或拒绝。


推荐阅读