Firebase -> Date Order Reverse

firebase - date order reverse

The Firebase Database will always return results in ascending order. There is no way to reverse them.

There are two common workaround for this:

  1. Let the database do the filtering, but then reverse the results client-side.
  2. Add an inverted value to the database, and use that for querying.

These options have been covered quite a few times before. So instead of repeating, I'll give a list of previous answers:

  • Display posts in descending posted order
  • Sort firebase data in descending order using negative timestamp
  • firebase sort reverse order
  • Is it possible to reverse a Firebase list?
  • many more from this list: https://www.google.com/search?q=site:stackoverflow.com+firebase+reverse%20sort%20javascript

Sorting in descending order in Firebase database

Unfortunately firebase doesn't allow returning by descending order. I have generally just reversed the order of the results returned client side.

If your data query is too large to sort client side you can do

firebase.database().ref('books').orderByChild('ups').limitToLast(2)

and then invert the results from there. Documentation can be seen here

Firebase Data Desc Sorting in Android

Firebase can order the items in ascending order by a given property and then returns either the first N items (limitToFirst()) or the last N items (limitToLast()). There is no way to indicate that you want the items in descending order.

There are two options to get the behavior you want:

  1. Use a Firebase query to get the correct data, then re-order it client-side

  2. Add a field that has a descending value to the data

For the latter approach, it is common to have a inverted timestamp.

-1 * new Date().getTime();

How to reverse timestamp to order documents by latest in firestore

If you add an UNIX timestamp (or serverTimestamp) in your document you should be able to sort them in descending order.

db.collection("posts")
.orderBy("created", "desc")
.limit(10)
.get()

This query should fetch 10 latest documents i.e. sorts documents by the value of created field in descending order and limits to first 10 results.

While adding the document, you can add timestamp this way:

const timestamp = Date.now()

docRef.add({
created: timestamp,
...otherFields
})

You can use serverTimestamp itself as it has several benefits over Date.now() as explained by @Renaud. When you fetch the document then that created field will be an object as follows:

{
created: {
seconds: 1627370100,
nanoseconds: 0
}
}

You can then use toDate method to convert that to a Javascript Date.

const {created} = snapshot.val()
console.log(created.toDate()) // JS Date object
console.log(Date.parse(created.toDate())) // Timestamp in milliseconds

Off-topic but you should return promises in a cloud function so add a return keyword:

return docRef.add({}).then(() => {
^^^^^^
console.log("Doc added")
return
}).catch((e) => {
console.log(e)
return null
})

Sort items in descending order by the number of childs count Firebase Realtime Database

That's not possible directly in the Firebase query. You would have to fetch the data once which will be in ascending order, then reverse that and process it using Javascript yourself.

const db = firebase.database()
db.ref("posts").once("value").then((snapshot) => {
const rawData = []
snapshot.forEach((post) => {
const postName = post.name
const upvotes = Object.keys(post.upvotes).length
const downvotes = Object.keys(post.downvotes).length
rawData.push({name: postName, upvotes: upvotes, downvotes: downvotes, score: upvotes - downvotes })
})
console.log(rawData)
})

Now the only part left is you would have to sort this array based on the property score.

I have a few suggestions:

  1. This data structure is not ideal or economical. Firestore would have been a better choice both for structure and querying but this existing structure can be improved a bit.
  2. There is no property called ".size" as mentioned in your screenshot. You must store a count of upvotes and downvotes explicitly in their respective nodes. Then you would be able to use .orderByChild("upvotes.size") in the query.

Let me know if you need more clarification.

How to order documents by timestamp automatically in firebase?

Firebase Realtime Database always returns results in ascending order. There is no way to order descending order.

This means you have two common options:

  1. Reverse the nodes on the client.
  2. Store an inverted value in a property, and order on that.

If you want to retrieve a subset of the items, keep in mind that you can combine any of these approaches with limitToFirst() and limitToLast. For example, to get the 10 most recent messages, you could:

  1. order on timestamp
  2. get the last 10 items
  3. reverse them client-side

Also see:

  • How to get data from firebase in descending order of value?, which shows an example of storing an inverted score.
  • Sorting in descending order in Firebase database, which shows someone using the limitToLast approach mentioned above.
  • Display posts in descending posted order, which shows how to invert a date value. Please ignore the use of priorities, as you'd nowadays just store the inverted value in a regular property and use orderByChild().
  • Many more links from this list.


Related Topics



Leave a reply



Submit