Home > database >  How to sort firebase storage bucket by the newest (by date descending)?
How to sort firebase storage bucket by the newest (by date descending)?

Time:11-17

Can you help me? I'm having trouble sorting files in the Firebase Storage bucket. I knew the list() and listAll() functions will not help me sort, so I tried using timestamps for naming those files. It worked but in ascending order, I'm looking for a way to make the order descending. Thank you.

I tried naming the file with a timestamp but it make the order ascending. I'm expecting descending order (the newest on top).

CodePudding user response:

The simplest solution for solving this problem would be to store the details for each image in the Firestore database. So each image would be represented by a document. So your database structure should look like this:

db-root
 |
 --- images (collection)
      |
      --- $imageId (document)
           |
           --- name: "My awesome image"
           |
           --- url: "https://..."
           |
           --- timestamp: November 16, 2022 at 2:46:19 PM UTC 3

Now, you only have to perform a query and specify the direction:

val db = Firebase.firestore
val query = db.collection("images").orderBy("timestamp", Query.Direction.DESCENDING)

When using this approach, there is no need to provide a timestamp for the time. You can name them whatever you want.

  • Related