Clint
Clint

Reputation: 387

How to retrieve autoId to delete value

I am trying to allow users to delete comments upon pressing the delete button. When comments are submitted, they're created using autoId and the header of the node will be the postId to see what post they commented on.

  "comments" : {
    "-LmfZZis5ovtBwfm_4xR" : {
      "-LoHu5Qv3BmuHTsSlthj" : {
        "creationDate" : 1.567980283717026E9,
        "text" : "Kkkk",
        "uid" : "64r3dgTN6xMhHYhptFlsFWX0dLk2"
      },
      "-LoHuPohuQ3eUtDWL_G-" : {
        "creationDate" : 1.567980367209054E9,
        "text" : " Ok",
        "uid" : "64r3dgTN6xMhHYhptFlsFWX0dLk2"
      }
    }
  },

I do not know how to retrieve the autoId so current logged in users can delete their comments. Here is the code for submission


  func didSubmit(for comment: String) {

        guard let uid = Auth.auth().currentUser?.uid else { return }

        print("post id:", self.post?.postId ?? "")

        print("Inserting comment:", comment)


        let postId = self.post?.postId ?? ""
        let values = ["text": comment, "creationDate": Date().timeIntervalSince1970, "uid": uid] as [String : Any]

        Database.database().reference().child("comments").child(postId).childByAutoId().updateChildValues(values) { (err, ref) in

            if let err = err {
                print("Failed to insert comment:", err)
                return
            }

            self.uploadCommentNotificationToServer()

            if comment.contains("@") {
                self.uploadMentionNotification(forPostId: postId, withText: comment, isForComment: true)
            }

            self.containerView.clearCommentTextView()
        }

        }

Comment struct


struct Comment {
    var commentId: String!
    let user: User
    var creationDate: Date!
    let text: String
    let uid: String!

    init(commentId: String!,user: User, dictionary: [String: Any]) {
        self.commentId = commentId
        self.user = user
        self.text = dictionary["text"] as? String ?? ""
        self.uid = dictionary["uid"] as? String ?? ""

        if let creationDate = dictionary["creationDate"] as? Double {
            self.creationDate = Date(timeIntervalSince1970: creationDate)
        }

    }

    var post: Post?


    func deleteComment() {
        guard let postId = self.post?.postId else { return }

     let commentsRef = Database.database().reference().child("comments")
        commentsRef.child(postId).child(commentId).removeValue()




    }




}


Code to fetch the comments


    var comments = [Comment]()

    func fetchComments() {
        guard let postId = self.post?.postId else { return }
        let ref = Database.database().reference().child("comments").child(postId)
        ref.observe(.childAdded, with: { (snapshot) in
             let commentId = snapshot.key
            guard let dictionary = snapshot.value as? [String: Any] else { return }

            guard let uid = dictionary["uid"] as? String else { return }

            Database.fetchUserWithUID(with: uid, completion: { (user) in
                let comment = Comment(commentId: commentId, user: user, dictionary: dictionary)

                self.comments.append(comment)
                self.collectionView?.reloadData()
            })

        }) { (err) in
            print("Failed to observe comments")
        }
    }

Thanks!

Upvotes: 0

Views: 56

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599011

To be able to delete a node, you must know the full path to that node.

There are two ways to know the key of the product you want to delete:

  1. You've passed it along your app from the moment when you loaded the data.
  2. You have some other value that allows you to perform a query on the database to look up the key.

The first option is the most common, as you'll typically be loading the data from the database already to display it to the user. In that case you should "simply" pass the key of the data along when displaying the value.

Once you have the key of the product/child node, you can delete it with:

let postId  = "-LmfZZis5ovtBwfm_4xR"
let commentId  = "-LoHu5Qv3BmuHTsSlthj"
let commentsRef = Database.database().reference().child("comments")
commentsRef.child(postId).child(commentId).removeValue()

Upvotes: 1

Related Questions