5

In Firebase realtime database, autogenerating ids keeps all entries in chronological order of when they were created. Firestore seems to be completely random. Is there a way to create ids the same way they're generated in database? Or do I need to pass a creation timestamp and sort by this?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
rharding
  • 551
  • 1
  • 3
  • 14

2 Answers2

5

From the Firestore documentation on adding data:

Important: Unlike "push IDs" in the Firebase Realtime Database, Cloud Firestore auto-generated IDs do not provide any automatic ordering. If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents.

So you indeed will need to add a timestamp field to the documents if you want to order chronologically. You can use server-side timestamps for that, as shown in the Firestore documentation on updating data:

docRef.update({
  timestamp: firebase.firestore.FieldValue.serverTimestamp()
});

With that you can order chronologically both in the console and in your own queries.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

Is there a way to create ids the same way they're generated in Database?

No, there is not! Unlike the Fireabse realtime database ids, Cloud Firestore ids are actually purely random. There's no time component included. That's why there is no order. The collisions of ids in this case is also incredibly unlikely and you can/should assume they'll be completely unique. That's what they were designed for.

Or do I need to pass a creation timestamp and sort by this?

You are guessing right, you should order your items according to a timestamp property.

For Android, here you can find how to add the date using a model class or FieldValue.serverTimestamp().

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193