1

I use Google Firestore as database in my project. It creates random generated id's for document names. I understood it's made with an purpose and I must use timestamp as a field in my document to order them by time they created.

On the other hand I also need a field that increase sequentially every time a new object added to the database. And I need to show customers this field because it will contain Order Id.

What is the best practice and how to create a field sequentially increased every time a new object created. How to manually increase new item realted field?

Sorry if it is an easy question, I am just lost. Any help is appreciated.

Eren Tüfekçi
  • 2,463
  • 3
  • 16
  • 35
  • 1
    "What is the best practice and how to create a field sequentially increased every time a new object created. " The best practice is to not do that. But my answer to the linked questions explains how to do it if you really must. – Frank van Puffelen Dec 06 '19 at 22:59
  • Actually I read your response while investigating, but couldn't make it clear. Now it started make sense. Thanks for the fast response @FrankvanPuffelen – Eren Tüfekçi Dec 06 '19 at 23:09

1 Answers1

1

Seeing that you want a sequential order ID, you can probably maintain a document that stores a counter of the latest order ID.

Every time you want to add a new document, increment the order ID and use it to store it in the new document key or data.

As of now it is not possible to do the increment and at the same time read the latest value in a single operation. You would want to do it in a Firestore Transaction as explained in the answer of another question here. I suggest you read the question and the other answers in that thread as they are useful.

Joshua Chan
  • 1,797
  • 8
  • 16