partizan
partizan

Reputation: 295

Firebase Order By a Date Value from Today Doesn't Work

How can I fetch data ordered by a date field value? I want to show all events based on their starts field value from now()? I didn't think it will be that hard but I can't get it to properly work.

My firebase data is:

    "events" : {
      "-KwX5oG6TYNWWhLYC5rx" : {
        "ends" : "2018-01-04T23:30:47.071Z",
        "starts" : "2018-01-02T23:30:47.062Z",
        "title" : "Event 1" 
      },
      "-L0Id2D34D2Sd2T5oyXX" : {
        "ends" : "2017-12-27T23:30:39.566Z", 
        "starts" : "2017-12-26T23:30:39.552Z",
        "title" : "Event 2"
      }
    } 

The code to query firebase data:

  const today = new Date().toISOString(); 
  const ref = FirebaseRef.child("events").orderByChild('starts').startAt(today);

  return ref.on('value', (snapshot) => {
    const events = snapshot.val() || {};

    // DO SOMETHING
  });

I tried storing data as Unix timestamp as well instead of ISO string and still didn't work.

Upvotes: 2

Views: 1610

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

Most likely the problem is caused by the fact that you do snapshot.val() on the query result. When you request ordered data from the Firebase Database, you get back three things: the keys, the values, and the order of the items.

When you call val() on a snapshot you get back a JSON representation of the value, which has room for only the keys and the values. And since the order of properties in a JSON object is undefined, the order of your results is undefined (though most browsers show them ordered by key).

To solve this problem, use Snapshot.forEach() to iterate over the result in the snapshot:

return ref.on('value', (snapshot) => {
  var events = [];
  snapshot.forEach((child) => {
   events.push(child.val());
  });
  console.log(events);
});

Upvotes: 3

Related Questions