【问题标题】:Firebase deleting value not working properlyFirebase 删除值无法正常工作
【发布时间】:2018-05-08 13:00:23
【问题描述】:

我想删除当前用户或当前 uid 的帖子。发帖用户的 uid 在 JSON 中由 String:uid 指定。所以我在快照中搜索 uid,如果它存在,我删除该 uid 的父级。问题是所有帖子都会被删除,而不仅仅是存储当前 uid 的帖子。

JSON 树

Posts
    -LBzjsl0Yfwdyh9xg6D2 (this is random uid)

           photoUrl: "https://firebasestorage.googleapis.com/v0/b/blo..."

           uid: "BBPHwd0RRibXFCvHcXA2aKbHoTm1" (this is uid of the current user)

代码:

let user = Auth.auth().currentUser?.uid

databaseRef.child("Posts").queryOrdered(byChild: "uid").queryEqual(toValue: user).observeSingleEvent(of: .value, with: { (snapshot) in


            if snapshot.exists() {


            //find out parent of current post
                let parent = snapshot.ref.parent!.key
                let ref = Database.database().reference()
                print (parent)
                func remove(child: String) {
                    ref.removeValue { error, _ in

                    }
                }
                remove(child: parent)

【问题讨论】:

  • 你能不能更好地解释一下父母和孩子是什么?另外,您到底要删除什么,而要删除什么?
  • 请查看这些steps 以帮助澄清您的问题。
  • 我想删除当前用户或当前uid的帖子。发帖用户的 uid 在 JSON 中由 String:uid 指定。所以我在快照中搜索 uid,如果它存在,我删除该 uid 的父级。问题是所有帖子都会被删除,而不仅仅是存储当前 uid 的帖子。
  • 您是否尝试过移除孩子而不是父母?

标签: swift firebase firebase-realtime-database


【解决方案1】:

当您对 Firebase 数据库执行查询时,可能会有多个结果。所以快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。

所以你的snapshot 变量包含一个结果列表。该 list 的父节点是 Posts 节点。所以如果你删除父节点,所有节点都会被删除。

要仅删除与您的查询匹配的节点,您需要遍历snapshot 的子节点并删除这些节点:

databaseRef.child("Posts").queryOrdered(byChild: "uid").queryEqual(toValue: user).observeSingleEvent(of: .value, with: { (snapshot) in
  for child in (snapshot?.children)! {           
    (child as AnyObject).ref.removeValue()  { error, _ in
    }
  }
}

【讨论】:

  • 是我需要使用的完整代码块还是我将值传递给 removeValue()?因为当我复制它给我一个错误“不能在'DataSnapshot'类型的非可选值上使用可选链接”
  • 啊。 removeValue() 不需要任何值。但它可能是ref? 和/或child?
  • 我将其更改为:for child in (snapshot.children) { child.ref.removeValue() { error, _ in } } 但我仍然收到关于子值的错误“类型值'Any' 没有成员 'ref'"
  • 显然 swift 调试器修复了值问题,因此代码现在看起来像这样: for child in (snapshot.children) { (child as AnyObject).ref.removeValue() { error, _ in } } 效果很好!
  • 我不明白的是循环如何只删除我想要删除的值?我没有传入任何特定的值..?
猜你喜欢
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多