0

I am now working on Firebase using RESTful api. I am having a sample data that looks like this

{
  "user1" : {
    "Name" : "John Doe",
    "acctStatus" : "Pending",
    "Liked" : "Y"
  },
  "user2" : {
    "Name" : "Jane Doe",
    "acctStatus" : "Done",
    "Liked" : "Y"
  }
}

So what I am trying to do is to retrieve a data where acctStatus is Pending and Liked is equals to Y. This is what my api url looks like

https://firebase.com/user.json?orderBy="acctStatus"&equalTo="Pending"&orderBy="Liked"&equalTo="Y"

However, when I does that, I retrieves both user1 & user2. Why is that so?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Arane
  • 323
  • 4
  • 19

1 Answers1

2

You are trying to chain multiple orderBy which is not allowed in Firebase. This is because too many queries would affect the performance in a negative way and Firebase kind of wants to force you to optimize your data structure.

So there are multiple options for you to go from here. Check out this post to see the possibilities with the real-time database: Query based on multiple where clauses in Firebase

I'd recommend you one of these two approaches.

1. Use the new Cloud Firestore

Firebase recently launched their new Cloud Firestore, which is basically a document based database. This makes structuring your data a lot easier and you get the ability to chain queries without affecting the performance in a bad way. Here you can learn more: https://firebase.google.com/docs/firestore/use-rest-api

and this is some helpful extra resource on how to structure your query: Firestore REST API starting query

2. Restructure your Database

If you decide to restructure your database I'd recommend you one of the following structures.

Add the status as a node:

{
  "pending": {
    "user1" : {
      "Name" : "John Doe",
      "Liked" : "Y"
    },
  },
  "done": {
    "user2" : {
      "Name" : "Jane Doe",
      "Liked" : "Y"
    }
  }
}

and now simply change your request to the following:

https://firebase.com/pending.json?orderBy="Liked"&equalTo="Y"

or as a second option you can make us of a combined property like this:

{
  "user1" : {
    "Name" : "John Doe",
    "acctStatus" : "Pending",
    "Liked" : "Y",
    "queryProp" : "Pending-Y"
  },
  "user2" : {
    "Name" : "Jane Doe",
    "acctStatus" : "Done",
    "Liked" : "Y",
    "queryProp" : "Done-Y"
  }
}

and then simply order by the queryProp:

https://firebase.com/user.json?orderBy="queryProp"&equalTo="Pending-Y"

The combined property is easier to maintain since you don't need to move the data around if your status changes. But keep in mind you will always receive the queryPropas part of your results.

Orlandster
  • 4,706
  • 2
  • 30
  • 45