[英]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.我正在使用 AngularFire 与 FireStore 数据库进行交互的 Angular 9 项目。
I have this code snippet that correctly perform an insert on a collection of my FireStore database, it works fine:我有这个代码片段可以在我的 FireStore 数据库集合上正确执行插入,它工作正常:
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.
我想检索与插入文档相关的文档UID 。 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?
我认为我必须将此行为实现到定义到then()运算符中的 function 中(我不完全确定这个断言)但是如何? 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?如何检索此代码插入的新文档的 UID?
The add()
method returns "a Promise resolved with a DocumentReference
pointing to the newly created document after it has been written to the backend." add()
方法返回“一个 Promise 解析,其中一个DocumentReference
在写入后端后指向新创建的文档。”
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.