检查孩子是否有具体的价值
当用户决定删除他的帐户时,我想删除用户发布的所有内容。检查孩子是否有具体的价值
所以我想通过数据库并删除包含他的userId的所有内容。
let userId = API.User.CURRENT_USER?.uid
API.Post.REF_POST.observeSingleEvent(of: .value) { (Post) in
if let dict = Post.value as? [String: Any] {
print("dict", dict)
let uid = dict["uid"] as? String
print(uid)
print(userId)
if uid == userId {
print("gefunden")
}else {
print("nichts")
}
}
}
这将打印出nil作为uid。 我仍然可以打印出所有的后期数据。
"posts" : {
"-Kt1h76YbyIqmSRkkLsv" : {
"bookmarkCount" : 0,
"caption" : "Helm ",
"characterCount" : 5,
"commentCount" : 0,
"creationDate" : 1.504357677437253E9,
"likeCount" : 0,
"photoUrl" : "https://firebasestorage.googleapis.com/v0/b/funcloud-8e84e.appspot.com/o/Posts%2F2B9606C8-E28D-4F69-9956-036192D36948?alt=media&token=2cd8712b-ca18-44a9-aa1d-d42e179a8eb7",
"ratio" : 1.5056179775280898,
"score" : -24,
"uid" : "hUhEPEg99HMkas6CqMXE4ZIyu472"
},
"-Kt1msnhcK4sxGKi5cae" : {
"bookmarkCount" : 0,
"caption" : "",
"characterCount" : 0,
"commentCount" : 0,
"creationDate" : 1.50435918759132E9,
"likeCount" : 0,
"photoUrl" : "https://firebasestorage.googleapis.com/v0/b/funcloud-8e84e.appspot.com/o/Posts%2F5E96D809-AF10-4FD7-B18A-4D138DDD4878?alt=media&token=16b9452b-25da-4f7b-9d93-80e557c91490",
"ratio" : 0.75,
"score" : 0,
"uid" : "hUhEPEg99HMkas6CqMXE4ZIyu472"
}
},
当currentUserId等于一个帖子,这意味着它已经被张贴正是用户的ID,我想删除整个帖子。
谢谢!
我认为你的数据库结构是错误的。 Firebase建议使用数据的平面表示
尝试在包含由他发送的帖子ID的用户下添加新节点。
user : {
userId : {
/* user data */
posts: {
postId1: true // the value isn't important
postIdX: true
}
}
name : username
}
posts : {
postId1: {
/*post data*/
}
}
现在你需要遍历您知道该URL的职位词典:
child("user/\(userId)/posts")
并为每个键恢复,你可以调用removeValue()方法,该方法将删除所有下的数据包含:
for (key, _) in dictionary {
Database.database().child("posts/(key)").removeValue()
}
希望这有助于你;)
我的建议是使用云functi以删除所有数据。
https://firebase.google.com/docs/functions/
在这里,你可以阅读更多关于它。 如果云功能管理这个过程,你不必担心,如果删除以某种方式失败,不良网络连接等发生。
好吧,我现在发现了它。以下是你如何遍历数据库的代码,看看一个孩子是否包含这个值,在我的例子中是userId。
let userId = API.User.CURRENT_USER?.uid
API.Post.REF_POST.observeSingleEvent(of: .value) { (snapshot) in
let arraySnapshot = (snapshot.children.allObjects as! [DataSnapshot])
// This is in order to take every single child into Account.
arraySnapshot.forEach({ (child) in
if let dict = child.value as? [String: Any] {
let uid = dict["uid"] as? String
//now I check every single child whether it contains the userId or now
if uid == userId {
print("gefunden")
Database.database().reference().child("posts").child(child.key).removeValue()
// I case the child contains the userId, I delete it. The child.key is the randomly created id of the child in which I am currently checking for the value.
} else {
print("nichts")
}
}
})
}
我的问题之前,是我刚打印出来的整个数据库,现在我期待为每个孩子在我的数据库,如果它包含我的用户的价值“UID”谁是要删除自己的帐户。
如果应用程序在这个过程中崩溃会发生什么? – barotia
我只想删除用户相关的东西,而不是一切。所以重要的是要知道这个值是否真的存在。 –
对不起,我已经修复了我的答案 –
谢谢你,但是,如何检查孩子是否具有特定的价值? –