Home > Software design >  Firestore: Save document ID into the Field
Firestore: Save document ID into the Field

Time:06-12

I'm using Swift here and confused about how to save the document ID into itself field. Here is an example :

I have a collection named "menu" menu collection

here we can focus on the one and only document in the "menu" collection which saved the name field "ayam goreng". How do i save the document ID " 7D3fuw3fri6oj287SySW" to the field named "menu_id" inside the document?

Thank you.

CodePudding user response:

As shown in the documentation on adding a document:

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([
    // ...
])

In your case, you can then get the document ID from the new ref with:

newCityRef.documentId
  • Related