gpt4 book ai didi

firebase - 如何在 Firebase 中按子值排序

转载 作者:行者123 更新时间:2023-12-02 08:05:58 25 4
gpt4 key购买 nike

我有这样的数据:

    scores: {
uid1: {
score: 15,
displayName: "Uciska"
},
uid2: {
score: 3,
displayName: "Bob"
},
uid3: {
etc...
}
}
我想按分数对它们进行排名,只保留前 100 名。
我是按照文档做到的。但它不起作用。即使分数发生变化,它也始终返回相同的顺序。
    const query = firebase.database().ref('scores')
.orderByChild('score')
.limitToLast(100)

query.on('child_added', snapshot => {
const score = snapshot.val().score
console.log(score)
})
我也在优化规则中添加了这一点,但我不确定它是否正确:
    "scores": {
".indexOn": ["score"]
}
正确的方法是什么?

最佳答案

您的代码是正确的,应该显示所需的结果。

由于 'child_added' 事件,您可能会遇到查看结果的困难,因为“监听器被传递了一个包含新 child 数据的快照”,如文档中的 here 详细说明。

您可以使用 once() 方法,如下所示,它会更清楚地显示结果,因为它将显示整个分数集。

    const query = firebase.database().ref('scores')
.orderByChild('score')
.limitToLast(100)

query.once('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
console.log(childData);
// ...
});
});

此外,您的规则可以写为 ".indexOn": "score",因为只有一个参数。

关于firebase - 如何在 Firebase 中按子值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51655326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com