skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search