8

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.

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
Fuad Adetoro
  • 244
  • 4
  • 10
  • Possible duplicate of [Firestore: How to get random documents in a collection](https://stackoverflow.com/questions/46798981/firestore-how-to-get-random-documents-in-a-collection) – Achref Gassoumi Nov 10 '17 at 16:56
  • @AchrefGassoumi That question is not really related to this question. Here, the user is asking how to generate random node keys in Firestore. In the question you linked, the user is how to randomly select nodes from the database (nothing to do with keys). My question here though - Firestore has a really a different mind set to storing data with collections and documents and really expands on the parent->Child model, which removes the reliance on random node keys. Can you provide a use case as to why you need a random string? – Jay Nov 10 '17 at 18:21

2 Answers2

10

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)")
    }
}
Todd Kerpelman
  • 16,875
  • 4
  • 42
  • 40
Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
  • 1
    But how else can I generate it if it's not going to be a documentPath? – Fuad Adetoro Nov 10 '17 at 19:40
  • I don't follow your question? Where else would it be? Remember Cloud Firestore is structured as collections & documents (which can have their own collections and documents), not as a giant JSON tree. – Dan McGrath Nov 10 '17 at 19:41
  • Is there a way of doing queryStarting(atValue: String, childKey: String) for Firestore? – Fuad Adetoro Nov 11 '17 at 18:08
  • It's best to ask other questions as a new question rather than in comments. More people will see it/find it that way. – Dan McGrath Nov 12 '17 at 04:59
6

To generate random id,

let ref = db.collection("somePath")
let docId = ref.document().documentID
elbert rivas
  • 1,464
  • 1
  • 17
  • 15