FlutterDeveloper11
FlutterDeveloper11

Reputation: 29

How to get the last document id in firestore with flutter?

I need to know the id of the last created document in firebase, as it is essential to upload another document with a higher id as I name my documents with index, so is there a way to get the last created document ?

Upvotes: 1

Views: 3315

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598603

Firestore has no built-in way to get the most recently inserted document. While it maintains when a document was created in its metadata, it doesn't have an API to query on this metadata.

So if you want to know which document was most recently inserted, you will have to add a field to each document that tracks when that document was created. You'll typically want to use a serve-side timestamp for that. With that field in each document, you can then perform a query for the most recent document with:

collectionRef.orderBy("createdAt", descending: true).limit(1)

Upvotes: 7

Related Questions