Firebase, orderByChild is not sorting
Firebase, orderByChild is not sorting
I'm trying to sort my snapshots by using orderByChild but this thing is not working.
FIREBASE RULES :
"rules":
"community":
"users":
".read": true,
"$uid":
".read": true,
".write": "$uid === auth.uid",
".indexOn": ["pseudo", "pseudoLower", "pseudoInverseLower", "films"]
DATA :
"community" :
"users" :
"Ab" :
"films" : 200,
"filters" : 2,
"id" : "Ab",
"pseudoBase" : "AB",
"pseudoInverseLower" : "zy",
"pseudoLower" : "ab"
,
"Bc" :
"films" : 692,
"filters" : 4,
"id" : "Bc",
"pseudoBase" : "King",
"pseudoInverseLower" : "prmt",
"pseudoLower" : "king"
,
"Ce" :
"films" : 100,
"filters" : 5,
"id" : "a",
"pseudoBase" : "A",
"pseudoInverseLower" : "z",
"pseudoLower" : "a"
JS :
db.ref('community/users').orderByChild('films').once('value', snap => )
In the user data you'll retrieve his pseudo (and the inverse), his films length and filters length.
I tried orderByChild('pseudoLower')
, .orderByChild('films')
and .orderByChild('pseudoInverseLower')
but nothing changed.
orderByChild('pseudoLower')
.orderByChild('films')
.orderByChild('pseudoInverseLower')
I'm really stuck at this point... Maybe I forgot something?
Seems as though
orderByChild
only works when using the child event types.– Callam
Sep 17 '18 at 22:33
orderByChild
@Callam: that's not true.
orderByChild
works for any event type that you choose to listen to.– Frank van Puffelen
Sep 17 '18 at 22:44
orderByChild
Hey Josselin. The code you shared does nothing with the
snap
yet. So it's hard to say what's going wrong. That said, based on past experience I expect you're not maintaining order. If that's the case, Callam's answer is your solution.– Frank van Puffelen
Sep 17 '18 at 22:47
snap
1 Answer
1
You need to convert the resultant snapshot into an array of children – this can be done using the snapshot forEach
method and this will iterate the children in order of the child key provided in the query. The users will lose the order they were received in if you print the snapshot value.
forEach
async function getCommunityUsers(filter)
const usersRef = admin.database().ref('community/users')
const snapshot = await usersRef.orderByChild(filter).once('value')
let users =
snapshot.forEach(child =>
users.push(
key: child.key,
...child.val()
)
return false
)
return users
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
When you say it's not working, I'm not sure what you mean. Can you update your question to include what you're expecting to happen and what's happening instead?
– Jen Person
Sep 17 '18 at 22:21