You have unlimited access as a PRO member
You are receiving a free preview of 3 lessons
Your free preview as expired - please upgrade to PRO
Contents
Recent Posts
- Object Oriented Programming With TypeScript
- Angular Elements Advanced Techniques
- TypeScript - the Basics
- The Real State of JavaScript 2018
- Cloud Scheduler for Firebase Functions
- Testing Firestore Security Rules With the Emulator
- How to Use Git and Github
- Infinite Virtual Scroll With the Angular CDK
- Build a Group Chat With Firestore
- Async Await Pro Tips
Negative Timestamps to Sort Records in Firebase
written by Jeff DelaneyIn 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 |
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) { } |
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() { |
And in the HTML
<div *ngFor="let post of posts | async"> |