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

后端 未结 6 1622

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

    As others mentioned also, we can get the document reference once it added. After we get the document reference on the behalf of id, we can update the same

    Service.ts file

    async funName(data: Data){
          let docRef = this.firestore.collection('table-name').add(data);
          console.log(docRef)
          try {
            const docAdded = await docRef;
            console.log(docAdded.id);
            this.firestore.doc('table-name/' + docAdded.id).update({ id: docAdded.id });
            return docRef;
          }
          catch (err) {
            return err;
          }
        }
    

    component.ts file

    async addData(){
        try{
          let res =  await this.dataServ.funName(this.form.value);
          this.snackbar.open('success', 'Success');
        }catch(ex){
          this.disabled = false;
          this.snackbar.open('err', 'Error')
          console.log(ex, 'exception');
        }
      }
    

提交回复
热议问题