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 pare two values of current payment and previous payment and display it's difference to user.
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 pare two values of current payment and previous payment and display it's difference to user.
Share Improve this question edited Oct 23, 2017 at 14:37 Frank van Puffelen 599k85 gold badges889 silver badges859 bronze badges asked Oct 23, 2017 at 10:16 Noman AliNoman Ali 3,34013 gold badges47 silver badges79 bronze badges1 Answer
Reset to default 13The 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.