Home > OS >  Save document ID when creating a document in Firestore
Save document ID when creating a document in Firestore

Time:01-31

I am making an iOS app where users can create posts. I let Firestore create an automatically generated id. I also want to save that id to the user's Firestore document. Is there a way to save that automatically generated id in a variable? Here's my Swift code:

Firestore.firestore().collection("Posts").document().setData([
      "user" : self.uid,
      "media" : url!,
      "text" : self.text,
      "date" : Date()  ])

Firestore.firestore().collection("Users").document(self.uid).updateData([
      "posts" : FieldValue.arrayUnion([*Document ID*])  ])

CodePudding user response:

From the Firebase documentation on adding data:

In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc():

let newCityRef = db.collection("cities").document()

// later...
newCityRef.setData([
   // ...
])

Behind the scenes, .add(...) and .doc().set(...) are completely equivalent, so you can use whichever is more convenient.

So you can split the creation of the document reference from writing to that reference too:

let newPostRef = Firestore.firestore().collection("Posts").document()
newPostRef.setData([
      "user" : self.uid,
      "media" : url!,
      "text" : self.text,
      "date" : Date()  ])

Firestore.firestore().collection("Users").document(self.uid).updateData([
      "posts" : FieldValue.arrayUnion([ newPostRef.documentID ])  ])
  •  Tags:  
  • Related