Search Lessons, Code Snippets, and Videos
search by algolia
X
#native_cta# #native_desc# Sponsored by #native_company#

Negative Timestamps to Sort Records in Firebase

written by Jeff Delaney
full courses and content on fireship.io

In this snippet, I will show you how to add negative timestamps to Firebase records to enable reverse server-side sorting of large datasets. A limitation of Firebase is that it is impossible to query a collection in reverse order, unless you load all data client-side first. Since this is not practical with large datasets, a reverse timestamp strategy is a possible solution.

This snippet is based on a stack overflow question I answered in plain JavaScript.

Data Strcuture with Reverse Timestamp

Let’s first look at how our data is structured in Firebase. It is just a simple collection of posts. Notice the timestamp of the last post is a smaller number than the more recent post.

posts
$pushKey1
timestamp: -123...
title: string;
$pushKey2
title: string;
timestamp: -124...

data structure of negative timestamps in firebase

Adding the Reverse Timestamp with AngularFire2

It is critical to use the Firebase server timestamp when using this strategy. Using the JavaScript Date object is tied a user’s local system, so using it will lead to unpredictable results. The challenge is that firebase.database.ServerValue.TIMESTAMP is an object, so we need to first create the db record with a normal timestamp, then retrieve it, then update with the negative value.

constructor(private db: AngularFireDatabase) {  }

createPost() {
let timestamp = firebase.database.ServerValue.TIMESTAMP
const title = 'Hello World'

/// Push new post to list
const ref = this.db.list('/posts')
const promise = ref.push( { timestamp, title} )
const key = promise.key

/// After successful push, get timestamp and overwrite with negative value
promise.then(_ => {
this.db.object('/posts/' + key)
.take(1)
.do(post => {
timestamp = post.timestamp * -1
this.db.list('/posts').update(key, { timestamp })
})
.subscribe()
})
}

Querying Data in Reverse

Now that we have negative timestamps on the database records, we can retrieve them in reverse order, so the most recent posts will be displayed first.

getPosts() {
this.posts = this.db.list('/posts', {
query: {
orderByChild: 'timestamp'
}
})
}

And in the HTML

<div *ngFor="let post of posts | async">
{{ post.title }}
{{ post.timestamp }}
</div>