Firebase, get immediate parent of a child with specific value

14,991

Solution 1

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...)

Solution 2

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

Solution 3

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)")
        })
Share:
14,991
Jacob Kaif
Author by

Jacob Kaif

Updated on June 20, 2022

Comments

  • Jacob Kaif
    Jacob Kaif almost 2 years

    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: 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