5

Basically summed up in the title, I would like to make it so that each new document being created in a particular collection has an increment sort of serial number to it. This is for properly tracking the new orders that are written to the database. AutoID is random and causes sorting issues, I would like the data to be easily manageable. Is this possible to achieve via Cloud Functions? Any sample code snippets I can look at? Thank you!

coder
  • 8,346
  • 16
  • 39
  • 53
Chris William
  • 205
  • 2
  • 5
  • 9
  • You should solve the sorting requirement by adding a field to the documents that contains your actual sorting order. Using sequential IDs for that is an anti-pattern with Firebase, since it will cause scalability problems. – Frank van Puffelen Jun 23 '18 at 01:22
  • Could you please elaborate why sequential IDs cause scalability issues? Also, any sample code which allows field serial numbering via Cloud Functions? – Chris William Jun 23 '18 at 19:38
  • The scalability comes from how Firestore spreads the document out over its storage layer. Simplified: sequential IDs have more hashing collisions, which means you hit write limitations sooner. Having IDs that are more random ensures the writes are spread out evenly across the storage layer. At read there is no such bottleneck, which is why the recommended approach is to use random keys, and a field for ordering upon reads. – Frank van Puffelen Jun 23 '18 at 22:33
  • instead of this you can solve your problem with a incremental property inside a document. or you can check here https://link.medium.com/JBLoRkvgz3 – BHAR4T Jan 26 '20 at 16:56

2 Answers2

4

Use firebase.firestore.FieldValue.serverTimestamp. It will be set by the server to nanosecond resolution.

firebase.firestore().collection('stuff').add({
  sort: firebase.firestore.FieldValue.serverTimestamp(),
});
abraham
  • 46,583
  • 10
  • 100
  • 152
1

As per @Frank van Puffelen comment, "Using sequential IDs for that is an anti-pattern". Your use case is also mentioned in the Firestore documentation here:

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.

LundinCast
  • 9,412
  • 4
  • 36
  • 48