使用负时间戳按降序对 Firebase 数据进行排序 [英] Sort firebase data in descending order using negative timestamp
问题描述
上面是我的 firebase 数据库的屏幕截图.我正在尝试使用负时间戳按降序对 firebase 数据进行排序.我正在使用以下命令:
above is a screenshot of my firebase database. i am trying to sort firebase data in descending order using negative timestamp. I 'm using the following command:
const feedRef = database.ref('ducks')
feedRef.orderByChild('timestamp').on('value', (snapshot, error) => {
const feed = snapshot.val()})
我一直以与数据库相同的顺序获取提要,而不是像我想要的那样按降序排列.我认为它不起作用,因为鸭子端点没有子名称时间戳我将如何实现这一目标?推送生成的密钥是否有时间戳数据?
i keep getting the feed in the same order as the database not in the descending order like i want.I think its not working because ducks endpoint doesnt have a child name timestamp how would i achieve this? Do the push generated keys have timestamp data ?
推荐答案
当您对快照调用 .val()
时,它会被转换为 JSON 对象.JavaScript 对象中的键根据定义是无序的(尽管许多实现会按字典顺序迭代键).
When you call .val()
on a snapshot, it gets converted into a JSON object. And the keys in a JavaScript object are by definition unordered (although many implementations will iterate the keys in lexicographical order).
如果您在 Firebase 数据库上运行查询,则必须确保在按正确顺序获取项目之前未将其转换为 JSON.在您的情况下,通过使用 DataSnapshot.forEach()
:
If you run a query on the Firebase Database, you must ensure you don't convert it to JSON before you get the items in the right order. In your case, by using DataSnapshot.forEach()
:
const feedRef = database.ref('ducks')
var feed = [];
feedRef.orderByChild('timestamp').on('value', (snapshot, error) => {
snapshot.forEach((duckSnap) => {
const duck = duckSnap.val()
console.log(duckSnap.key+'='+duck.name);
feed.push(duck);
});
});
console.log(feed);
这篇关于使用负时间戳按降序对 Firebase 数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!