Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase, get immediate parent of a child with specific value

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

like image 826
Jacob Kaif Avatar asked Aug 23 '17 09:08

Jacob Kaif


2 Answers

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

like image 180
André Düwel Avatar answered Nov 16 '22 21:11

André Düwel


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
like image 10
torinpitchers Avatar answered Nov 16 '22 19:11

torinpitchers