Sort firebase data in descending order using negative timestamp

岁酱吖の 提交于 2019-12-28 06:49:09

问题


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 ?


回答1:


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).

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);


来源:https://stackoverflow.com/questions/38548406/sort-firebase-data-in-descending-order-using-negative-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!