0

I have a query that searches for users based on their age:

self?.ref.child("users").queryOrdered(byChild: "age").queryStarting(atValue: "18").queryEnding(atValue: "25").observeSingleEvent(of: .childAdded, with:  { (snapshot) in
    print(snapshot)

My Firebase structure is like this:

users
    -> uid1
        -> age : "18"
        -> name : "Lisa"
        -> ...
    -> uid2
        -> age : "18"
        -> name : "Elizabeth"
        -> ...

In my DB there are two people withe age : "18".

Everything works well when queryStartingAtValue is "18".

The issue occurs when I change the queryStartingAtValue to the non-existing age (e.g. "19").

Indeed, no results are returned, the data seems to be blocked inside the query.

Do you have any idea what's wrong with this query?

Thx.

Kai Engelhardt
  • 1,272
  • 13
  • 17
Roha
  • 23
  • 6
  • can you explain what you mean by "blocked inside the query" – Justin Oroz Jun 16 '17 at 23:06
  • Hi! The query returns no value, not even null. Nothing happens. I tried with .value instead of .childAdded and it returns a null when it doesn't match with the age. This issue with .childAdded prevents me from checking if snapshot.exists (). – Roha Jun 16 '17 at 23:27

1 Answers1

0

In the data you show there are no nodes with 19 or higher, so the query doesn't match any nodes. In that case the .childAdded event does not fire.

If you want to detect this condition, you must listen to the .value event, which does fire even when there are no children. But you'll get a single .value event for all matching children in this case, so you'll need to loop over the child nodes:

self?.ref.child("users")
  .queryOrdered(byChild: "age").queryStarting(atValue: "18")
  .queryEnding(atValue: "25")
  .observeSingleEvent(of: .value, with:  { (snapshot) in
    print(snapshot.exists())
    for child in snapshot.children {
      ...
    }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807