Home > database >  Using a date as Firestore Document Id?
Using a date as Firestore Document Id?

Time:11-01

I have a diary App where I want to have a single document for each day. My question is if it would be a good practise to use an ISO 8601 datetime String as a document Id. Because every day can only have one document it would be an unique Id.

Or should I store the date in the document and use a random document Id? What would be a better choice?

One querie I want to do is check if there is an document with a specific date (for example today). If so, I want to fetch this document, otherwhise If there is no document for today I want to create one.

CodePudding user response:

Using the value that you want to be unique as the document ID is an easy (and in many cases the only) way to ensure uniqueness. As long as the limit on throughput for such sequential keys is acceptable for your use-case (which seems to be the case here), it is a good, simple method of ensuring uniqueness.

CodePudding user response:

It seems good, however firebase does not recommend this. This is because using incremental document id names is not recommended. This could be Customer1, Customer2, ... CustomerN, or in your case dates. 10-31-21, 11-1-21, 11-2-21, ... is incremental.

Also, note their second suggestion: Avoid using / forward slashes in document IDs.

Or should I store the date in the document and use a random document Id? What would be a better choice?

I would chose the latter. Use a random doc id and then store the date inside.

With this being said, best practices and exactly that, best practices. They are not rules. In your case, if using the date as the document id makes it easier and requires less reads, it may be the best choice.

  • Related