j.doe
j.doe

Reputation: 305

sorting doesnt work with queryOrdered in firebase realtime database

  "users":{
    "steve_rodriquez":{
        "ch1":{
             "timestamp":2
        },
        "ch2":{
            "timestamp":1
        },
        "ch3":{
            "timestamp":4
        },
        "ch4":{
            "timestamp":3
        }
    }   
}

Rules are defined as

 "rules": {
    ".read": true,
    ".write": true,
    "users":{
         ".indexOn": ["timestamp"] 
    }
  }

When i try to sort based on time stamp it doesnt work. i added 1,2,3,4 just for example

This is my client side code for it

ref = Database.database().reference()
        (ref.child("users").child("steve_rodriquez")).queryOrdered(byChild: "timestamp").observeSingleEvent(of: .value, with: {(snapshot) in
            print(snapshot.value as Any)
        })

Upvotes: 1

Views: 148

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600071

When you retrieve the data from Firebase, the snapshot contains the keys, the values, and the order of all child nodes. But when you call snapshot.value it needs to convert this to a Dictionary, which only has space for the keys and the values. So at this point the information about the order of the child nodes is lost.

To maintain the order of the child nodes, iterate over the snapshot.children as shown in the documentation on listening for child events, and for example this answer: Iterate over snapshot children in Firebase

Upvotes: 2

Related Questions