Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting second last record from firestore DB, javascript

As firestore is not that much old yet, there is very small help out there in some scenarios.

I am trying to get 2nd last record from Firestore but it's getting very first one. i know it's wrong query:

db.collection("batches")
  .where('added_at', "<", paymentData.added_at) //Here paymentData is last record
  .limit(1).get().then(function(prevSnapshot){
})

For example i have 3 records

A. added_at: 1 Jan, 2017
B. added_at: 2 Jan, 2017
C. added_at: 3 Jan, 2017

And i have C in paymentData right now and i want record B. But it's getting record A.

How do i get Second Last Record ?

EDIT:

Each record will always have newer timestamp than previous one (even it can be 1 Minute. e.g previous 27 Jan, 2017 5:20 PM and new 27 Jan, 2017 5:21 PM)

And paymentData will always have latest record.

Basically i want to compare two values of current payment and previous payment and display it's difference to user.

like image 466
Noman Ali Avatar asked Oct 23 '17 10:10

Noman Ali


People also ask

How do I get most recent documents on firestore?

Is there any way to get the last created document in Firebase Firestore collection? Yes, there is! The simplest way to achieve this is to add a date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. That's it!

How do I query multiple values in firestore?

Starting with… in queries! With the in query, you can query a specific field for multiple values (up to 10) in a single query. You do this by passing a list containing all the values you want to search for, and Cloud Firestore will match any document whose field equals one of those values.

What is onSnapshot in firebase?

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.


1 Answers

The order of Firestore documents is not guaranteed, unless you specifically order the documents in your query. To do this, you'll need to use the orderBy() method.

For example, you can specify that the database sorts your documents by the added_at field in descending order, which should return your desired result, B:

db.collection("batches")
  .orderBy('added_at', 'desc') // Order documents by added_at field in descending order
  .where('added_at', "<", paymentData.added_at)
  .limit(1).get().then(function(prevSnapshot){
          // ...
  })

Be careful though: multiple documents with the same timestamp, or timestamps in between the one you're expecting, may mean that you'll receive a different document than expected, so I wouldn't rely on this to pick specific documents.

like image 133
Grimthorr Avatar answered Oct 06 '22 16:10

Grimthorr