0

I want to sort a list in firebase realtime database using orderByChildValue(). But the value is inside an array.

How to do that?

Database

{
  "partners": [
    {
      "full_name": "Alex Smith",
      "partner_roles": {
        "role1": [
          {
            "latitude": 9.84945654,
            "locality": "location1",
            "longitude": 76.32834545
          },
          {
            "latitude": 9.81232145,
            "locality": "location2",
            "longitude": 76.34229345
          }
        ],
        "role2": [
          {
            "latitude": 9.84945654,
            "locality": "location1",
            "longitude": 76.32834554
          }
        ]
      }
    }
  ]
}

Here i want to return all the items role1/locality equals location2

i tried using:

database.child("partners")
            .orderByChild("partner_roles/role1/locality")
            .equalTo(location1)

But it returns empty and It returns items if the database is like:

{
  "partners": [
    {
      "full_name": "Alex Smith",
      "partner_roles": {
        "role1": {
          "latitude": 9.84945654,
          "locality": "location1",
          "longitude": 76.32834545
        },
        "role2": {
          "latitude": 9.84945654,
          "locality": "location1",
          "longitude": 76.32834554
        }
      }
    }
  ]
}
3
  • You can do something like this stackoverflow.com/a/68248939/9346054 Commented Feb 17, 2023 at 7:27
  • If the second approach works, why not use it? Please respond using @AlexMamo
    – Alex Mamo
    Commented Feb 17, 2023 at 12:11
  • @AlexMamo i am fetching the partners using users current location, and some partners services maybe available in multiple loctaions. So i am trying to add multiple locations. Commented Feb 18, 2023 at 9:02

1 Answer 1

0

The value to order/filter on must be at a fixed path under each child node of the path where you execute the query. That is not the case when the value is in an array. In fact, in your case there may even be multiple values for each node, which is something Firebase queries don't support.

As is common when dealing with NoSQL databases, the solution is to change or augment your data model to allow the use-case. Since you're looking to load partners by their locality, add a node with exactly that information. Something like:

{
  "partner_localities": {
    "location1": {
      "partner1": {
        "full_name": "Alex Smith",
        "role": "rol1"
      }
    }
  }
}

Now you can find all partners at location1 by loading the data from partner_localities/location1. I've duplicated some of the data about the partner in the node, but you should tune that to whatever works best for your data model.

Also see:

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.