Reputation: 27
Is there a way to sort documents in collection chronologically when they are created? Currently, they are all over the place. For example, in To-Do app, when you add new item to collection, it should display at the bottom, last, not somewhere in the middle.
Upvotes: 1
Views: 49
Reputation: 317352
You will need to define an order based on some data in the document, and order your queries based on that field.
The typical solution for time-base order to make sure your documents all contain a timestamp field that you can use to sort them. When you call add() (or other methods to update data), you can tell Firestore to use the current time using FieldValue.serverTimestamp():
collection(...).add({
..., // your other fields
createdOn: FieldValue.serverTimestamp()
})
Then you can use that field to sort when querying with orderBy():
collection(...).orderBy('createdOn')
Upvotes: 2
Reputation: 1341
Try using DateTime.now()
for the document ID. This should put the collection in chronological order.
For example:
Firestore.instance.collection('Posts').document(DateTime.now().toString()).setData({});
Upvotes: 0