简体   繁体   English

如何对 Firebase 实时数据库 v9 进行排序和限制?

[英]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.我是 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.因为我使用了 orderbyValue、orderbykey 和 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. snapshot.val() 返回一个对象,其中包含无序且不知道如何访问 all 或循环的对象(检查底部)。 for limiting, I tried limitToLast which works fine but sorting doesn't.为了限制,我尝试了 limitToLast 工作正常,但排序没有。
help me to sort and limit this.帮我整理和限制这个。

this is how my data is stored in realtime database这就是我的数据在实时数据库中的存储方式

这就是我的数据的存储方式

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('scores'));
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

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.正如 Dharmaraj 评论的那样:快照中的结果实际上是有序的,但是当您调用snapshot.val()它会被转换为 JSON 对象,并且 JSON 对象中的键根据定义没有排序。

To get the results in order, loop over them with snapshot.forEach :要按顺序获得结果,请使用snapshot.forEach遍历它们:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM