uci*_*ska 3 firebase firebase-realtime-database
我有这样的数据:
scores: {
uid1: {
score: 15,
displayName: "Uciska"
},
uid2: {
score: 3,
displayName: "Bob"
},
uid3: {
etc...
}
}
Run Code Online (Sandbox Code Playgroud)
我想按分数对它们进行排名,只保留前 100 名。
我是按照文档做到的。但它不起作用。即使分数发生变化,它也始终返回相同的顺序。
const query = firebase.database().ref('scores')
.orderByChild('score')
.limitToLast(100)
query.on('child_added', snapshot => {
const score = snapshot.val().score
console.log(score)
})
Run Code Online (Sandbox Code Playgroud)
我也在优化规则中添加了这一点,但我不确定它是否正确:
"scores": {
".indexOn": ["score"]
}
Run Code Online (Sandbox Code Playgroud)
正确的方法是什么?
您的代码是正确的,应该显示所需的结果。
您可能会遇到困难,看到的结果是由于'child_added',因为“听众传递包含新的子数据快照”,因为详细的事件在这里的文档。
您可以使用该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);
// ...
});
});
Run Code Online (Sandbox Code Playgroud)
此外,您的规则可以写成".indexOn": "score"因为只有一个参数。
| 归档时间: |
|
| 查看次数: |
8341 次 |
| 最近记录: |