Ruben
Ruben

Reputation: 1859

Firebase queryOrderedByChild not ordering by name in Swift

I have in the security & rules option this:

{
 "rules": {
 ".read": true,
 ".write": true,
 "groups": {
    ".indexOn": "name"
  } 
 }
}

And my JSON structure is like this:

{
"groups": {
    "-KAti17inT7GbHEgbzzS": {
        "author": "ruben",
        "name": "C"
   },
   "-KAti36BQGO8sRmfufkE": {
        "author": "ruben",
        "name": "D"
   },
   "-KAti2CVAHtJllQm_m-W": {
        "author": "ruben",
        "name": "A"
   }
}

As you can see, it is not ordered by "name", as is it supposed to be. What I'm doing wrong?

Upvotes: 0

Views: 1039

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600100

That .indexOn instruction in the security rules only tells the database to create an index on the name property. It doesn't automatically re-order the data.

In addition: the order of keys in a JSON object is undefined.

To get a list of your groups by name, you have to execute a Firebase query. From the Firebase documentation on queries:

let ref = Firebase(url:"https://dinosaur-facts.firebaseio.com/dinosaurs")
ref.queryOrderedByChild("height").observeEventType(.ChildAdded, withBlock: { snapshot in
    if let height = snapshot.value["height"] as? Double {
        println("\(snapshot.key) was \(height) meters tall")
    }
})

If you adapt this snippet to your data structure, it will print the groups in the correct order.

Upvotes: 2

Related Questions