MHDev MHDev - 20 days ago 11
iOS Question

How can I delete just the parent key for a Firebase value?

I am fairly new to using Firebase and I am struggling to access just the parent key to delete the value.

I am currently trying to access the parent key using the following code:

if let exerciseName = exercises[indexPath.row].exerciseName {

let ref = FIRDatabase.database().reference().child("userExercises")

ref.queryOrdered(byChild: "exerciseName").queryEqual(toValue: exerciseName).observe(.childAdded, with: { (snapshot) in

print(snapshot.ref)

})

}


My data structure looks likes this image, but when I print the values out if there is another user with the same
exerciseName
in the database it prints out all of the parent keys.

How can I only delete the record I have selected to delete?

When I
print(snapshot)
the result is:

Snap (-KWw9hg2Uiyo9_cj7TAy) {
bodyPart = Back;
exerciseName = "Test 2";
userId = 8rHmyTxdocTEvk1ERiiavjMUYyD3;
}
Snap (-KWwAGd3t9vsW0LHKtV1) {
bodyPart = Arms;
exerciseName = "Test 2";
userId = PO8p0UoqqHOas3D9Ise8CgWT3PN2;
}

Answer

try:

    let ref = FIRDatabase.database().reference().child("userExercises")        
    let filteredRef = // do some query,sorting ...

    filteredRef.observe(.value, with: { snapshot in
        for item in snapshot.children {
            guard let itemSnapshot = item as? FIRDataSnapshot else { break }
            guard let dict = itemSnapshot.value as? NSDictionary else { break }

            let id = itemSnapshot.key // this is the record id of an exercise !
        }
    }

To delete one of your records:

    let ref = FIRDatabase.database().reference().child("userExcercises").child(record_id) // see above how to fetch the id
    ref.removeValue()

I would suggest you restructure your userExcercises like so:

{
    "userExcercises" : {
        "<USER-ID>" : {
            "<EXCERCISE-ID>" : {
                "bodyPart" : "Back",
                "excerciseName" : "Test02"
            },
            // lots of more excercises for this user ...
        },
        // lots of more users ...
     }
}

(to be clear: is the uid of the authenticated user, is a autogenerated ( childByAutoId() ) id )