I have a problem with ordering queries in firebase real-time database. I'm querying object, with objects sorted by timestamp. But it returns object with objects sorted by keys.
async function pushResult(username: string, testResult: TestResult) {
const userResultsRef = ref(db, `results/${username}`);
try {
await set(userResultsRef, testResult);
} catch (error) {
throw error;
}
}
That function pushes result object. And then I try to query the last five, results objects ordered by timestamp.
async function getLastFive() {
const lastFiveResultsQuery = query(
ref(db, "results"),
orderByChild("created_at"),
limitToLast(5)
);
try {
const response = await get(lastFiveResultsQuery);
const firebaseResults = response.val() as FirebaseResults || {};
console.log(firebaseResults);
const output = firebaseResultsToArray(firebaseResults);
return output.reverse();
} catch (error) {
console.log(error);
throw error;
}
}
It return me object with my username keys and result properties.
{
"user1": {
"accuracy": 100,
"cpm": 100,
"created_at": 1678709252777,
"language": "english",
"wpm": 110
},
"user2": {
"accuracy": 100,
"cpm": 100,
"created_at": 1678709261007,
"language": "english",
"wpm": 110
}
//...
}
It's returned it order that I do not expect, because objects should be ordered by created_at property