RedMess
RedMess

Reputation: 11

Query firebase data using keys or fields in nested subobjects?

my receipe data in firebase ![my receipe data in firebase][1]

My receipe data looks like the following

receipe/1/12: "{"itemno":"1","receipeno":"12","receipedescript..."

How can I filter all receipes where receipeno = 12 or starting with receipeno = 12, irrespective of itemno?

I have tried the following, but got no results or errors? Also tried startAt

this.query = this.db.database.ref("receipe").orderByChild("receipeno").equalTo("12").limitToFirst(100);

BTW: this.query = this.db.database.ref("receipe") this returns all data and this.db.database.ref("receipe/1") returns all receipe for itemno == 1.

I have updated the data to not use opaque strings. [Updated db so as not to use opaque strings][2]

and have tried the following.

this.query = this.db.database.ref("receipe").orderByChild("itemno").equalTo("1").limitToFirst(100);

And

this.query = this.db.database.ref("receipe").orderByChild("receipeno").equalTo("r1").limitToFirst(100);

Upvotes: 0

Views: 264

Answers (1)

user663031
user663031

Reputation:

Firebase is not going to help you with deep queries. It filters and sorts at one level. Therefore, there is no way to say, "find me all the recipes with an id (or recipeno) of 12, under any node under recipes.

If you had a single level, then you would do orderByKey().equalTo("12"). Of course this will limit you to one recipe per ID.

If you are going to have multiple recipes with the number 12 and want to do this kind of querying, you need to change your database structure--essentially getting rid of the intermediate level where you currently have keys of 1, 2 etc. Most likely in this case you would use automatically generated keys of the kind that result from push, such as:

+ recipes
  + autokey1: {itemno, recipeno, recipedescription}
  + autokey2: {itemno, recipeno, recipedescription}

Then you could say

orderByChild('recipeno').equalTo('12')

This assumes, of course, as pointed out in a comment, that you are saving the data as objects, not as stringified JSON, which Firebase will never be able to query against the insides of.

This is a good case study of the notion that you should design your Firebase database structure carefully in advance to allow you to do the kinds of querying you will need to do.

By the way, this question has nothing to do whatsoever with Angular.

Upvotes: 1

Related Questions