Reputation: 45
So, consider the following data structure:
{
"speed" : {
"scores" : {
"aHOBsddilrQ2lX3fal8v" : {
"RrbEpWwfEAeVpnbXabSP" : {
"event" : 959140,
"judge" : "Svante",
"zETdMyzb2OWgrVq9GJwv" : {
"score" : 65,
"timestamp" : 1466355355
},
"Jd0wtYEs74A2wc47LI7F" : {
"score" : 75,
"timestamp" : 1466355465
}
}
}
}
}
}
Is there a way to get the score of the deepest child with the newest timestamp's score if I know authuid
and the value of event:
but neither of the randomid's (both are unique)
I've tried different approaches with for ()
and .orderBy[Child|Key|Value]().equalTo().limitToLast(1);
(none of which looks good enough to even bother sharing...) which didn't work. I have one extremely dirty and hacks solution currently that'll break if I add one more value to the second deepest part of the tree (using for
and .length - 3
) is there a way to do this cleaner?
Upvotes: 0
Views: 231
Reputation: 598728
The Firebase Database can query nested children, but only if you know the path. What you are looking for goes a bit beyond Firebase's querying capabilities, which always have to balance query power with the realtime nature of the database.
As usual with NoSQL databases, the solution is to change the data model to suit your needs. For this case, I'd set up a node that has the latest score for each event under that event's id:
{
"speed" : {
"mostRecentScoresPerEvent" : {
"event959140": {
"score" : 75
}
}
}
}
Now you can update the score with a simple set operation:
ref.child('speed/mostRecentScoresPerEvent/event'+eventId).set(42);
And read it using:
ref.child('speed/mostRecentScoresPerEvent/event'+eventId).on('value',...
Upvotes: 2