Home > OS >  how save data to Firebase Firestore with a custom but unique Id?
how save data to Firebase Firestore with a custom but unique Id?

Time:09-19

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?

CodePudding user response:

If you want to set your own ID then you just have to specify it in document() as shown below:

let ref = dbLocations.collection("Data").document("CUSTOM_ID")
ref.setData(data);

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.

CodePudding user response:

How can I generate an ID as "location1" or "location2"

Using sequential document IDs is considered an anti-pattern when it comes to Firestore:

Do not use monotonically increasing document IDs such as:

  • Customer1, Customer2, Customer3, ...
  • Product 1, Product 2, Product 3, ...

Such sequential IDs can lead to hotspots that impact latency.

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:

let ref = dbLocations.collection("Data").document("idOfYourChoice")
  • Related