0

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
ruslanonly
  • 41
  • 5
  • 1
    You need to use the `forEach()` method, see the duplicate. `response.forEach((childSnapshot) => {console.log(childSnapshot.val());});` – Renaud Tarnec Mar 13 '23 at 13:29

0 Answers0