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.
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.
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.
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.
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.
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)")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With