aekit
aekit

Reputation: 405

how to sort and limit firebase realtime db v9?

devs. I am trying to make a table that will show the top scorers. I am new to firebase v9.

problem: I am using realtime DB for storing the name and scores of users with doc names and names are same. as I used orderbyValue, orderbykey and orderbyChild. snapshot.val() returns an object which contains objects ( check at the bottom ) which is unordered and don't know how to access all or loop. for limiting, I tried limitToLast which works fine but sorting doesn't.
help me to sort and limit this.

this is how my data is stored in realtime database

this is how my data is stored

this is my code to fetch and try to sort

import { getDatabase, ref, set, onValue, query, orderByChild, limitToLast, equalTo, orderByValue, orderByKey } from "https://www.gstatic.com/firebasejs/9.4.1/firebase-database.js";
var namelist = $('.person');
var list = $('.scores');
// const scoreBoardRef = ref(db, 'users');
const scoreBoardRef = query(ref(db, 'users'), orderByChild('score'));
onValue(scoreBoardRef, (snapshot) => {
    const data = snapshot.val();
    console.log(data); // this returns object containing object and **i don't know how to deal with this.**
    //console.log(scoreBoardRef);
    list[0].textContent = data.score; // here i want score
    namelist[0].textContent = "";//here i want name
//my main goal is to loop through top 3 or 10 data and print it to table

}); 

In the console, this is what I get

⬇{abcd: {…}, man2: {…}, nacho: {…}, two: {…}}
 ▶abcd: {name: 'abcd', score: 15}
 ▶man2: {name: 'man2', score: 20}
 ▶nacho: {name: 'nacho', score: 21}
 ▶two: {name: 'two', score: 18}
 ▶[[Prototype]]: Object

Upvotes: 1

Views: 783

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599706

As Dharmaraj commented: the results in the snapshot are actually ordered, but when you call snapshot.val() it gets converted to a JSON object and the keys in a JSON object are by definition not ordered.

To get the results in order, loop over them with snapshot.forEach:

onValue(scoreBoardRef, (snapshot) => {
  snapshot.forEach((child) => {
    const data = child.val();
    console.log(data);
}); 

Upvotes: 2

Related Questions