简体   繁体   中英

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

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?

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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM