Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Unique ID in Cloud Firestore

I'm having trouble generating a random Unique ID using Cloud Firestore. Previously I was using the Realtime Database and to generate a random string I use the childByAutoID().key.

Is there a way of doing something similar for Cloud Firestore?

As Jay said in the comments this isn't a duplicate as I'm trying to generate a random string, I'm not trying to get random documents.

like image 575
Fuad Adetoro Avatar asked Nov 10 '17 16:11

Fuad Adetoro


People also ask

How to check if a document is unique in Cloud Firestore?

Natively, the Cloud Firestore provides us with no uniqueness check from either Rules or the SDK. But, of course, there is a workaround. You can use Firestore queries to get the document ID which corresponds to the field you want to keep unique.

How do I ramp up parallel reads gradually in Cloud Firestore?

Ramp up parallel reads gradually to ensure that Cloud Firestore can handle traffic to the new collection. A possible strategy for gradually ramping up reads or writes to a new collection is to use a deterministic hash of the user ID to select a random percentage of users attempting to write new documents.

How to enable uniqueness for a field value in FireStore?

Currently, there is no way for you to enable uniqueness in field values in the whole database. There is a quick workaround, though with queries that you can use. You want to enforce uniqueness for a field value in your Firestore database for your app. An app where users have their profiles and a unique username assigned to them.

How can I improve the performance of my Cloud Firestore API?

If your application accesses Cloud Firestore through the REST or RPC APIs directly instead of through an SDK, your application should implement transaction retries to increase reliability. For the best snapshot listener performance, keep your documents small and control the read rate of your clients.


1 Answers

If you create the document without an explicit Id, our SDK will auto-generate a random one for you.

// Add a new document with a generated id.
var ref: DocumentReference? = nil
ref = db.collection("messages").addDocument(data: [
    "sender": "<my_senders_id>",
    "recipient": "<my_recipient_id>",
    "message": "Hello from Google Cloud Platform & Firebase!",
    "status": "unread"
]) { err in
    if let err = err {
        print("Error adding document: \(err)")
    } else {
        print("Document added with ID: \(ref!.documentID)")
    }
}
like image 130
Dan McGrath Avatar answered Sep 19 '22 23:09

Dan McGrath