Since firestore is not very old, it can be of little help in some cases.
I’m trying to get the second record from Firestore but it’s getting the first. I know this is the 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
I now have C
in paymentData and I want record B
. But it is getting record A
.
How do I get the second last record?
Edit:
The timestamp of each record is always newer than the previous one (even though it can be 1 minute. For example, the previous 27 Jan, 2017 5:20 PM
and the new one 27 Jan , 2017 5:21 PM
)
And paymentData will always have the latest record.
Basically I want to compare two values Current payment and Previous payment and show the difference between it and the user.
1> Grimthorr..:
The ordering of Firestore documents is not guaranteed unless you specifically order the documents in the query. To do this, you need to use the orderBy()
Method.
For example, you can specify that the database sorts documents by the added_at
field in descending order, which should return the desired results 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 the timestamp you’re expecting between one, may mean you’ll receive a different file than expected, so I wouldn’t rely on this to pick specific File.