Delete a specific child node in Firebase swift

只愿长相守 提交于 2021-01-28 11:20:34

问题


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

My database looks like this:

• 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

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.


回答1:


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....")...

Or more idiomatic:

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

(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()


来源:https://stackoverflow.com/questions/52688644/delete-a-specific-child-node-in-firebase-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!