user8320179
user8320179

Reputation: 3

firebase parent id returned instead of child id

I am new to firebase, I am using ionic for the first time as well to develop a chat application. I have a database with a similar structure as shown below

tutors:
"Ben Clarke":
    email:"[email protected]"
    name: ben clarke
"James Gall":
   email:[email protected]
   name: james gal

I am trying to get the Id of the tutors using the email. I have tried using the guide that I have found here and on firebase doc to do this:

`firebase.database().ref('tutors').orderByChild('email').equalTo(this.myTutor)
  .once('value')
  .then(snapshot => {
    var records = snapshot.key;
    var chilkkey= snapshot.val();
    this.tutorID=records;
    this. uid = chilkkey;
  })

`I want the result to give me 'Ben Clarke' the child id but instead it returns 'tutors' which is the parent id. Please, any idea on what I am doing wrong. Thanks

Upvotes: 0

Views: 391

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

If you then on the snapshot request the key, it's the key of the location that you originally ran the query on. To get the key of the specific child/children that were matched by the query, you need to loop over the result:

firebase.database().ref('tutors').orderByChild('email').equalTo(this.myTutor)
  .once('value')
  .then(snapshot => {
    snapshot.forEach(function(child) {
      console.log(child.key);
    });
  })

Upvotes: 1

Related Questions