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

后端 未结 6 1619

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:43

    If you want to use async/await instead of .then(), you can write it like this:

    const post = async (doc) => {
        const doc_ref = await db.collection(my_collection).add(doc)
        return doc_ref.id
    }
    

    If you want to catch any errors in this function, include .catch():

        const doc_ref = await db.collection(my_collection).add(doc).catch(err => { ... })
    

    or you can have the calling function catch the error.

提交回复
热议问题