0

我在 Firebase 中有peopleWhoLike一个peopleWhoLike名为我可以删除它,但该值没有被删除。

func removeLike(postID: String){
    ref.child("posts").child(postID).observe(.value, with: { (snapshot) in
        if let info = snapshot.value as? [String : AnyObject]{
            if var peopleWhoLike = info["peopleWhoLike"] as? [String : String]{
                print("peopleWhoLike - \(peopleWhoLike)")
                for person in peopleWhoLike{
                    if person.value == FIRAuth.auth()!.currentUser!.uid{
                        peopleWhoLike.removeValue(forKey: person.key)
                        print("personkey - \(person.key)")
                    }
                }
            }
        }
    })
}

两个打印语句都打印正确,即person.key是正确的键

截屏

任何帮助将不胜感激谢谢!

4

1 回答 1

0

您那里只有数据的快照(副本)

从 firebase 数据库中删除该值;尝试这个:

//path should be like this (i guess):
let currentUserUid = FIRAuth.auth()!.c‌​urrentUser!.uid
ref.child("posts")
   .child(postId)
   .child("peopleWhoLike")
   .chi‌​ld(currentUserUid)
   .rem‌​oveValue()

或相同:

let currentUserUid = FIRAuth.auth()!.c‌​urrentUser!.uid
ref.child("posts/\(postId)/peopleWhoLike/\(currentUserUid)").rem‌​oveValue()

更新

您想删除人员密钥 - 然后您可以:

a) 遍历 peopleWhoLike 并查找它是否是用户(但请把它let currentUserUid = FIRAuth.auth()!.c‌​urrentUser!.uid放在循环之外!

//path should be like this (i guess):
let currentUserUid = FIRAuth.auth()!.c‌​urrentUser!.uid

// loop and when match `person.value == currentUserUid` then:
ref.child("posts")
   .child(postId)
   .child("peopleWhoLike")
   .chi‌​ld(person.key)  //<-- change here
   .rem‌​oveValue()

b)您在查询中搜索。然后删除生成的节点。

ref.child("posts")
   .child(postId)
   .child("peopleWhoLike")
   .startAt(currentUserId)
   .endAt(currentUserId)
   . [...] do something

我不知道你是否可以.removeValue()在这一点上直接打电话。但是您可以使用 SingleEvent 和快照snapshot.ref.removeValue()- 在删除之前仔细检查。但是由于这会导致引用,因此您应该可以直接调用.removeValue()

ref.child("posts")
   .child(postId)
   .child("peopleWhoLike")
   .startAt(currentUserId)
   .endAt(currentUserId)
   .removeValue()

注意:此搜索比直接路径花费更长的时间

请参阅此处的文档进行查询:

https://firebase.googleblog.com/2013/10/queries-part-1-common-sql-queries.html#byemail

https://firebase.google.com/docs/database/ios/read-and-write#delete_data

笔记:

我建议您使用userUidas 键保存它,因为您只需要在线删除(请参阅我的第一个代码片段,您不需要从中获取所有数据peopleWhoLike)并将值设置为 1 或者您可以保存当前日期(然后您知道当它被喜欢时)

于 2017-01-28T15:12:58.843 回答