Jonah Elbaz
Jonah Elbaz

Reputation: 325

Remove an entire child from Firebase using Swift

I'd like to write a function to remove an entire child from Firebase. I'm using XCode 10 and swift 3+.

I have all the user info of the child I'd like to delete so I assume the best call would be to iterate through every child and test for the matching sub child value but it would be great if there was a faster way. Thanks for the help!

Heres what I'd like to delete

enter image description here

I assume testing for epoch time then removing the whole node would be ideal. Also not sure how to do this

Upvotes: 2

Views: 5148

Answers (1)

Felipe Ferri
Felipe Ferri

Reputation: 3598

I understand you don't have access to the key of the node you want do delete. Is that right? Why not? If you use the "observe()" function on a FIRDatabaseQuery object, each returned object should come with a key and a value.

Having a key it is easy to remove a node, as stated in the Firebase official guides.

From the linked guide,

Delete data

The simplest way to delete data is to call removeValue on a reference to the location of that data.

You can also delete by specifying nil as the value for another write operation such as setValue or updateChildValues. You can use this technique with updateChildValues to delete multiple children in a single API call.

So, you could try:

FirebaseDatabase.Database.database().reference(withPath: "Forum").child(key).removeValue()

or

FirebaseDatabase.Database.database().reference(withPath: "Forum").child(key).setValue(nil)

If you can't get the key in any way, what you said about "iterating" through the children of the node could be done by using a query. Here's some example code, supposing you want all forum posts by Jonahelbaz:

return FirebaseDatabase.Database.database().reference(withPath: "Forum").queryOrdered(byChild: "username").queryEqual(toValue: "Jonahelbaz").observe(.value, with: { (snapshot) in
    if let forumPosts = snapshot.value as? [String: [String: AnyObject]] {
        for (key, _) in forumPosts  {
                FirebaseDatabase.Database.database().reference(withPath: "Forum").child(key).removeValue()
        }
    }
})

Here you create a sorted query using as reference "username" then you ask only for the forum posts where "username" are equal to Johanelbaz. You know the returned snapshot is an Array, so now you iterate through the array and use the keys for deleting the nodes.

This way of deleting isn't very good because you might get several posts with the same username and would delete them all. The ideal case would be to obtain the exact key of the forum post you want to delete.

Upvotes: 7

Related Questions