Reputation: 42957
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?
Upvotes: 1
Views: 511
Reputation: 83103
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);
});
Upvotes: 2