0

I am trying to fetch my data based on 2 things. First, fetch where isFromCreator = true. Second, fetch the results in terms of the latest 10.

My db structure looks like this:

ClubContent
     CreatorID
         clubID
            postID: {isFromCreator: Bool}

I then attempt to fetch this content like this:

        ref.child("ClubContent").child("jhTFin5npXeOv2fdwHBrTxTdWIi2").child("1622325513718")
        .queryOrdered(byChild: "timestamp")
        .queryLimited(toLast: 10)
        .queryEqual(toValue: true, childKey: "isFromCreator")
        .observeSingleEvent(of: .value, with: { (snapshot) in

The result returned however is an empty snapshot. What is going wrong?

Awsome_user
  • 55
  • 11

1 Answers1

2

The second argument to queryEqual(toValue:) is not the key on which to filter, but the so-called disambiguation key. So if there are multiple node matching the value, the database finds the one whose key is equal to childKey and starts returning nodes from there.

So if you want to filter on isFromCreator, you will need:

ref.child("ClubContent").child("jhTFin5npXeOv2fdwHBrTxTdWIi2").child("1622325513718")
    .queryOrdered(byChild: "isFromCreator")
    .queryEqual(toValue: true)

Then if there are multiple child nodes with isFromCreator equal to true, you can determine which one to start returning nodes from by passing its key as an extra value in to .queryEqual(toValue:), for example:

    .queryEqual(toValue: true, childKey: "-Lasdnsa39132...")

It seems you're trying to sort/filter on two properties, which is not possible in the Realtime Database. Firebase Database queries can only order/filter on a single property.

In many cases it is possible to combine the values you want to filter on into a single (synthetic) property. You could for example have a property: "isFromCreator_timestamp": "true_128348712" and order/filter on that.

For another example of this and other approaches, see my answer here: Query based on multiple where clauses in Firebase

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