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
        }
      }
    }
  ]
}
Mubashir P A
  • 11
  • 1
  • 4

1 Answers1

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807