1

I have the following FIREBASE realtime database structure Structure

And I would like to display these data sorted by date on my client side like

  • 1-9-2021
  • 13-07-2021
  • 10-12-2021
  • 10-1-2022
  • 11-1-2022

This is my code to display the data on my client side:

`getLogsAction(action) { this.listeDate = []; this.selected = true;

console.log('action: ' + action);
console.log('tab: ' + this.tabName);
console.log('solution: ' + this.service.idSolution);

this.afs
  .list('logs/' + this.tabName + '/' + this.service.idSolution + '/' + action)
  .snapshotChanges()
  .subscribe(ok => {
    this.logsInfos = [];
    ok.forEach(elem => {
      this.listeDate.push(elem.key);
    });
  });

}`

'action' is my Node 'Connection' which contains others nodes like '12-1-2022, 13-7-2021...' which contains for each node the metadata.

in my client view the code gives me the following display: Display in app So the display is exactly like the order of the structure in my database.

The real trouble here is that I have to sort 'a key node' and not a child. I know it exists orderByKey() , but I don't know how to use it in my case.

How can I sort these data by ascending ('above' get most recent date to 'bellow' the most old date) ?

Thanks !

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Dorian
  • 17
  • 8

1 Answers1

1

While the keys in your data may read like dates to you, in the database they actually are strings. And Realtime Database orders string values lexicographically.

The only way to get the result you want is to store the dates in a string format that meets your needs, i.e. a string format where the lexicographical order is the same as the chronological order. The most common format to use for this is ISO-8861, which would be:

"2022-09-01": ...,
"2022-10-01": ...,
"2022-10-03": ...

So to meet the use-case, you'll have to store your data in this format. The only alternative is to retrieve it as is, and then re-order the data in your code.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807