简体   繁体   中英

How to retrieve the UID of a document inserted into a FireStore collection from my Angular code using Angular Fire?

I am working on an Angular 9 project using AngularFire to interact with FireStore databse.

I have this code snippet that correctly perform an insert on a collection of my FireStore database, it works fine:

this.db
        .collection("calendar")
        .add({ title: newEvent.title,
               start: firebase.firestore.Timestamp.fromDate(newEvent.start),
               end: firebase.firestore.Timestamp.fromDate(newEvent.end)
             })
        .then(function() {
          console.log(" event successfully written!");
        })
        .catch(function(error) {
          console.error("Error writing document event: ", error);
        });

I only have a problem. I want to retrieve the document UID related to the inserted document. I think that I have to implement this behavior into the function defined into the then() operator (I am not totally sure of this assertion) but how? I am not understanding what is the correct way to implement this behavior and maybe I am missing something.

How can I retrieve the UID of the new document inserted by this code?

The add() method returns "a Promise resolved with a DocumentReference pointing to the newly created document after it has been written to the backend."

So, the following should do the trick:

this.db
        .collection("calendar")
        .add({ title: newEvent.title,
               start: firebase.firestore.Timestamp.fromDate(newEvent.start),
               end: firebase.firestore.Timestamp.fromDate(newEvent.end)
             })
        .then(function(docRef) {    // <-----
          const docID = docRef.id;  // <-----
          console.log(" event successfully written!");
        })
        .catch(function(error) {
          console.error("Error writing document event: ", error);
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM