在Firebase Swift中删除特定的子节点 [英] Delete a specific child node in Firebase swift

查看:39
本文介绍了在Firebase Swift中删除特定的子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能帮我解决这个问题吗?我想删除数据库中的特定消息.

Can you help me solve this problem? I want to delete a specific message in the database.

我的数据库如下:

• MESSAGES  
 ••(childByAutoID XXXXXXXXX)  
  •••email: user1@gmail.com  
  •••message: hello there  
  •••timestamp: 329842938592  
•  
 ••(childByAutoID XXXXXXXXX)  
  •••email: user1@gmail.com  
  •••message: where are you?  
  •••timestamp: 872985042750  
•  
 ••(childByAutoID XXXXXXXXX)  
  •••email: user2@gmail.com  
  •••message: basketball?  
  •••timestamp: 845938459349

我尝试使用此代码,但它从当前用户(user1)删除了错误的帖子.

I tried using this code but it deletes the wrong post from the current user (user1).

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {


    if (editingStyle == .delete) {
        jobRequests.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)

        if let email = Auth.auth().currentUser?.email {

            Database.database().reference().child("MESSAGES").queryOrdered(byChild: "email").queryEqual(toValue: email).observeSingleEvent(of: .childAdded, with: { (snapshot) in

               snapshot.ref.removeValue()

那么我该如何删除消息你在哪里?"及其成员.

so how can i delete the message "where are you?" and its members.

推荐答案

查询需要与您要删除的内容匹配.

The query needs to match what you want to delete.

如果要删除文本为您在哪里?" 的消息,则应查询以下内容:

If you want to delete the message with text "where are you?", you should query for that:

let messagesRef = Database.database().reference().child("MESSAGES")

messagesRef.queryOrdered(byChild: "message").queryEqual(toValue: "where are you?")...

如果要删除带有特定电子邮件的所有邮件,则应查询该邮件:

If you want to delete all messages with a specific email, you should query for that:

messagesRef.queryOrdered(byChild: "email").queryEqual(toValue: "email1@gmail.com")...

如果要删除特定消息,则必须知道其密钥,然后:

If you want to delete a specific message, you must know its key and then:

messagesRef.queryOrderedByKey().queryEqual(toValue: "-L....")...

或更惯用的:

messagesRef.child("-L....").observeSingleEvent(of: .value, with: { (snapshot) in
    snapshot.ref.removeValue()

(请注意,由于我们不再使用查询,因此此处观察的是 value 的值,而不是 .childAdded .

(Note that we're observing value here, not .childAdded, since we're no long using a query.

或更简单;由于您已经知道要删除的节点的完整路径,因此您无需读取任何内容:

Or even simpler; since you already know the full path of the node to delete, you don't need to read anything:

messagesRef.child("-L....").removeValue()

这篇关于在Firebase Swift中删除特定的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆