Reputation: 107
I'm trying to retrieve the key, using only the value, in Firebase.
Am working in Swift, for IOS
Trying to write a function that would like to return "hey", when given only the users email address "[email protected]"
Basically have the value at hand, and would like to retrieve the key, am trying to just delete the entry.
Anyone have any suggestions?
Here's the bit im unsure of.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCellEditingStyle.delete) {
let friendsSelectedEmail = friendsEmailsFromFirebase[indexPath.row]
let refToUserFriendList = fir.child("mybuddies").child(userID)
print(friendsSelectedEmail)
//query for the key of the email address, then use that to delete the object
//Or is there an easier firebase method?
self.tableView.reloadData()
}
}
**edit
In a nutshell, i just wanna delete this key-value pair, and I have access to only the value(email address), is that doable via a single firebase method? **assuming i dont use the better structure that @jay posted.
Upvotes: 0
Views: 73
Reputation: 35657
It appears the intention here is to use the hey part of [email protected] as the key.
A better approach is to create the child nodes with childByAutoId and store the properties within that node. So your structure becomes
zCu.....
email: "[email protected]"
buddy_name: "Leroy"
domain: "hey.com"
Then you can simply query all nodes for email that equals "[email protected]" which will return a snapshot that also has the user_name (hey) and domain (hey.com if needed)
If you need the code for that query, let me know. Keep in mind Firebase is asynchronous so it doesn't really "return" a value. You work with the value within the closure following the query.
From a comment, it appears we want to remove the buddy_name and email but leave the node. If the node is known, you can just create that reference, otherwise you can query for it. Either way you'll get the parent key to the node
let buddyRef = parent_node_key.child("buddy_name")
let domainRef = parent_node_key.child("domain")
buddyRef.setValue("")
domainRef.setValue("")
Keep in mind that I left email in this case as if we delete that, then the entire node will go away; a node must have at least one value to exist.
To add some clarity;
To create that structure, you would need to know the users uid which is used as a key or if you want it in another node, use .childByAutoId to create the key.
let ref = thisUsersUid //or let ref = your_firebase.childByAutoId()
ref.child("email").setValue("[email protected]")
ref.child("domain").setValue("hey.com")
ref.child("buddy_name").setValue("Leroy")
Upvotes: 1