0

I am not able to find a firebase object by specifying the specifiv child key and only if I specify the entire path to the object. Why is this?

This works

ref.child(`users/${user.uid}/watchlist/${key}`)
  .once('value')
  .then(function(snapshot) {
    console.log(snapshot.val());
});

This doesn't work

ref.child(key)
  .once('value')
  .then(function(snapshot) {
    console.log(snapshot.val());
});

My firebase connection

export const ref = firebase.database().ref()
Alex Miles
  • 301
  • 3
  • 7

1 Answers1

1

I'm not sure how else you would expect it to work? child() is not a "search" function, it only looks at direct children of the reference or child paths that you specify. It does not look through nested paths Firebase structure "searching" for the specified key. That would be incredibly inefficient. And even if it did do that, what would happen if there were multiple matching keys? Would it return all of them? What if they were at different depths? Etc.

The Firebase real time database is basically a big JSON-like data tree. The only way to get to a bit of data that you want is to know the entire path to that data. Otherwise there wouldn't be any structure at all.

I suppose if you wanted to, you could load the entire Firebase data structure and then write your own function for finding arbitrary keys, no matter where they were in the tree. But that has the same problematic inefficiencies as if it were built into the Firebase library itself - which, it is not.

Perhaps this will illustrate better how child() works. This:

ref.child(`users/${user.uid}/watchlist/${key}`);

Is basically the same as this:

ref.child("users").child(user.uid).child("watchlist").child(key);

Although I suspect that the second method is less efficient, I don't know for sure.

jered
  • 11,220
  • 2
  • 23
  • 34
  • Great answer Jered. Slight clarification: Firebase queries allow you to search paths with a single dynamic part. Also see my answer here: https://stackoverflow.com/questions/27207059/firebase-query-double-nested – Frank van Puffelen Jul 21 '17 at 21:06
  • If uids are unique then specifying specific children in the db would work however I don't know if that would be efficient but efficiency isn't the point of my concern. – Alex Miles Jul 22 '17 at 04:48