Firestore - How to get document id after adding a document to a collection

后端 未结 6 1631

Is there a way to acquire the document id that was generated after adding a document to a collection?

If I add a document to a collection that represents a \"post\"

6条回答
  •  余生分开走
    2020-12-08 04:50

    Here's what I do, as mentioned in your question. Not sure if it is best practice, but it works for easy access.

    When creating the document in the first place

    firebase.firestore().collection("cities").doc().set({ name: Tokyo,
    country: Japan })
    

    you can set the id of the doc and put that exact id in it as a property:

    firebase.firestore().collection("cities").doc('id-generated-from-somewhere')
    .set({ id: 'id-generated-from-somewhere', name: Tokyo, country: Japan })
    

提交回复
热议问题