Reputation: 159
I am working on an ios app with firebase backend. As users register, user node is created in firebase under which there are different children like email, name, avatar etc. What I am doing is that I am searching for some email in user nodes and if I find that email in some node, I want to get its parent key i.e -Ksdd23d2djhsdgjhs. See the image:
I want to get the value with upper arrow if the email matches with the one I have.
I have an email address and I am searching through all of the children in user node and then further check inside the to compare the email with the one I have. If email matches, I want to get its parent node like in the image it is Dn2LUAwdolg..... .
I can get the first node under user node. Assume that the node Dn2LU.. shown in picture is at some unknown position and I have to search all users to get its name if it's email child value matches with the one I am comparing it with.
Hope it's clear now
Upvotes: 9
Views: 17308
Reputation: 64
Well in my case I have other UID's under the UID needed that to load my friendship List:
For that, I have created this method
class func downloadAllFriendList(UserID:String, completion: @escaping (UserSimplifiedCredentials?) -> Swift.Void) {
var ref = Database.database().reference().child("Friendship").child(UserID).observe(.childAdded, with: { (snapshot) in
print("the child parent id is +++++++> \(snapshot.key)")
})
}
Upvotes: 0
Reputation: 562
I think what you are looking for is documented here: https://firebase.google.com/docs/reference/js/firebase.database.Reference#equalTo
I am no IOS developer, but I here is a JS example:
// Find all users which match the child node email.
var ref = firebase.database().ref('user');
ref.orderByChild('email').equalTo('[email protected]').on("value", function(snapshot) {
snapshot.forEach((function(child) { console.log(child.key) });
});
Tthe snapshot contains the whole node, but snapshot.key will return the node key (in your example: Dn2LUAwdolg...)
Upvotes: 12
Reputation: 159
I am answering my question but i will upvote @André's answer which helped me accomplish what i wanted. I am posting here the Swift 3.0 code i wrote while considering André's code.
let idtosearch = email
let ref = Database.database().reference().child("user")
ref.queryOrdered(byChild: "email").queryEqual(toValue: idtosearch).observeSingleEvent(of: .childAdded, with: { (snapshot) in
print("\(snapshot.key)")
})
Upvotes: 2
Reputation: 1292
you can grab the reference from the snapshot using .ref
and then grab the parent of the reference using .parent
on the child's reference then use .key
to grab the key of that reference which will be the parent key in your example: Dn2LUAwdolgf6HCn11UiSihejty1
So we have for example on the snapshot for avata
snapshot.ref.parent.key
which will equal in your case
Dn2LUAwdolgf6HCn11UiSihejty1
Upvotes: 10