Darwind Darwind - 6 months ago 38
Swift Question

Querying in Firebase by child of child

I have a structure of objects in Firebase looking like this:

-KBP27k4iOTT2m873xSE
categories
Geography: true
Oceania: true
correctanswer: "Yaren (de facto)"
languages: "English"
question: "Nauru"
questiontype: "Text"
wronganswer1: "Majuro"
wronganswer2: "Mata-Utu"
wronganswer3: "Suva"


I'm trying to find objects by categories, so for instance I want all objects which has the category set to "Oceania".

I'm using Swift and I can't really seem to grasp the concept of how to query the data.

My query right now looks like this:

ref.queryEqualToValue("", childKey: "categories").queryOrderedByChild("Oceania")


Where
ref
is the reference to Firebase in that specific path.

However whatever I've tried I keep getting ALL data returned instead of the objects with category Oceania only.

My data is structured like this:
baseurl/questions/


As you can see in the object example one question can have multiple categories added, so from what I've understood it's best to have a reference to the categories inside your objects.

I could change my structure to
baseurl/questions/oceania/uniqueids/
, but then I would get multiple entries covering the same data, but with different
uniqueid
, because the question would be present under both the categories
oceania
and
geography
.

By using the structure
baseurl/questions/oceania/
and
baseurl/questions/geography
I could also just add
unique ids
under
oceania
and
geography
that points to a specific
unique id
inside
baseurl/questions/uniqueids
instead, but that would mean I'd have to keep track of a lot of references. Making a relations table so to speak.

I wonder if that's the way to go or? Should I restructure my data? The app isn't in production yet, so it's possible to restructure the data completely with no bigger consequences, other than I'd have to rewrite my code, that pushes data to Firebase.

Let me know, if all of this doesn't make sense and sorry for the wall of text :-)

Answer

I think this should work:

ref.queryOrderedByChild("categories/Oceania").queryEqualToValue(true)