0

I got score node in Firebase:

And under score node my data structure is as:

{
"jjTO29ziQ2SjrH5PFzY7ZMpSgjq1-Kak6FCyGtdy_kcEPd4K" =     {
    jjTO29ziQ2SjrH5PFzY7ZMpSgjq1 = "-Kak6FCyGtdy_kcEPd4K";
    score = 5;
};
"jjTO29ziQ2SjrH5PFzY7ZMpSgjq1-KbE_pgfUsukOm4uW0bx" =     {
    jjTO29ziQ2SjrH5PFzY7ZMpSgjq1 = "-KbE_pgfUsukOm4uW0bx";
    score = 4;
};

Question: Can I filter the data by score ?

I tried doing :

FIRDatabase.database().reference().child("scores").queryOrdered(byChild: "score").observeSingleEvent(of: .value, with: { (snapshot) in

        debugPrint(snapshot.value ?? "nil")

    })

But can't get the result ?

Picture 1

user3804063
  • 809
  • 1
  • 14
  • 32

1 Answers1

6

When you execute a query against Firebase, you get a FIRDataSnapshot that contains three pieces of information for each result:

  • its key
  • its value
  • its position relative to other nodes

When you're calling snapshot.value the snapshot is converted into a Dictionary. Unfortunately that dictionary can only hold key-value pairs, so you lose the information on the position of the nodes. So while the data in the snapshot is actually sorted correctly, you're throwing that information away.

The solution is to use the FIRDataSnapshots built-in children property to loop over the child nodes in the correct order. The Firebase documentation on querying has this sample of how to do that:

_commentsRef.observeEventType(.Value, withBlock: { snapshot in
  for child in snapshot.children {
    ...
  }
})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807