Mitchell Rodrigues
Mitchell Rodrigues

Reputation: 17

Delete specific value from firebase database using swift

Firebase Database

enter image description here

I tried using this bit of code but it doesn't seem to work. I take the name the user selects and store it in nameList.

Lets say I store Blake Wodruff in nameList[0]. How do I remove only that name?

var nameList = [String](repeating: "", count:100)

func remove() {

        print(nameList[countAddNames])
        
        let usernameRef =  Database.database().reference().child("Candidate 1").child("alton").child(nameList[countAddNames]);
        usernameRef.removeValue();
    }

Upvotes: 0

Views: 669

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598603

To write to or delete a node, you must specify its entire path. So to delete node 0 from your JSON, you'd do:

let usernameRef =  Database.database().reference().child("Candidate 1").child("alton").child("0");
usernameRef.removeValue();

Or a bit shorter:

let usernameRef =  Database.database().reference().child("Candidate 1/alton/0");
usernameRef.removeValue();

If you only know the name of the user you want to remove, you'll need to first look up its index/full path before you can remove it. If you have the data in your application already, you can do it in that code. Otherwise you may have to use a database query (specifically .queryOrderedByValue and .queryEqualToValue) to determine where the value exists in the database.

Also see: Delete a specific child node in Firebase swift


Once you remove a value from your JSON structure, Firebase may no longer recognize it as an array. For this reason it is highly recommended to not use arrays for the structure that you have. In fact, I'd model your data as a set, which in JSON would look like:

"alton": {
  "Jake Jugg": true,
  "Blake Wodruff": true,
  "Alissa Sanchez": true
}

This would automatically:

  1. Prevent duplicates, as each name can by definition only appear once.
  2. Make removing a candidate by their name as easy as Database.database().reference().child("Candidate 1/alton/Jake Jugg").removeValue()

For more on this, also see my answer to Firebase query if child of child contains a value

Upvotes: 1

Related Questions