In swift using Firebase, with:
let ref = dbLocations.collection("Data").document()
ref.setData(data)
Data added with a document Id like 40rprS6NshDHhZiI8YxJ
how can I generate an ID as "location1" "location2" or something but with the guarantee the is a unique one on the database?
2
Answers
If you want to set your own ID then you just have to specify it in
document()
as shown below:This however will overwrite the document if it already so you must check if document exists before writing data. You could use
.setData(data, merge: true)
so if document exists it’ll update it instead of totally replacing current data if that suits your requirements.Using sequential document IDs is considered an anti-pattern when it comes to Firestore:
So you can create your own unique IDs, as long as you are 100% sure that those IDs are unique.
Moreover, each time you call
.document()
without passing any argument, a new document ID is generated. If you need to have a custom ID then you should consider using: