0

I'd like to retrieve all instances where the targetUser is Johnny.

Firebase

The problem is that Firebase doesn't let me have .child() as null.

How can I do this?

This was my attempt -

readTargetUser = () => {
  allHistory = [];
  let myHistory = firebase
    .database()
    .ref("/locations")
    .child()
    .child("targetUser" === "Johnny")
    .limitToLast(5);
  myHistory.on("value", snapshot => {
    console.log(
      "Here I can see all info where the targetUser is Johnny",
      snapshot
    );
  });
};
Dharman
  • 30,962
  • 25
  • 85
  • 135
Wilfredo Casas
  • 419
  • 2
  • 6
  • 14
  • You've included a picture of the JSON tree in your question. Please replace that with the actual JSON as text, which you can easily get by clicking the Export JSON link in the overflow menu (⠇) of [your Firebase Database console](https://console.firebase.google.com/project/_/database/data/). Having the JSON as text makes it searchable, allows us to easily use it to test with your actual data and use it in our answer and in general is just a Good Thing to do. – Frank van Puffelen Dec 24 '19 at 15:28

1 Answers1

1

You're looking for a query, which in Firebase is done with:

  let myHistory = firebase
    .database()
    .ref("/locations")
    .child("GG99AaPQjMhr0kT1xFkazjHMUrm1")
    .orderByChild("targetUser")
    .equalTo("Johnny")
    .limitToLast(5);

For more on this, see the Firebase documentation on ordering and filtering data.


If you don't know the GG99AaPQjMhr0kT1xFkazjHMUrm1 node, there is no way to order/filter on the targetUser property, as Firebase database queries can only order on properties that are at a known path under each child.

See my answer here: Firebase Query Double Nested

The typical solution in that case is to create a so-called inverted index in your database, purely for this use-case. It's look something like:

targetUsers: {
  "Johnny": {
    "GG99AaPQjMhr0kT1xFkazjHMUrm1_1577194136959": true,
    ".../...": true
  }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807