如何使用 Angular Fire 从我的 Angular 代码中检索插入到 FireStore 集合中的文档的 UID?
How to retrieve the UID of a document inserted into a FireStore collection from my Angular code using Angular Fire?
我正在开发一个 Angular 9 项目,使用 AngularFire 与 FireStore 数据库交互。
我有这段代码片段可以正确地对我的 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);
});
我只有一个问题。我想检索与插入文档相关的文档 UID。我认为我必须将这种行为实现到 then() 运算符中定义的函数中(我不完全确定这个断言)但是怎么做呢?我不明白实现此行为的正确方法是什么,也许我遗漏了一些东西。
如何获取通过此代码插入的新文档的 UID?
add()
method returns "a Promise resolved with a DocumentReference
指向新建文档写入后台后。
所以,下面应该可以解决问题:
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);
});
我正在开发一个 Angular 9 项目,使用 AngularFire 与 FireStore 数据库交互。
我有这段代码片段可以正确地对我的 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);
});
我只有一个问题。我想检索与插入文档相关的文档 UID。我认为我必须将这种行为实现到 then() 运算符中定义的函数中(我不完全确定这个断言)但是怎么做呢?我不明白实现此行为的正确方法是什么,也许我遗漏了一些东西。
如何获取通过此代码插入的新文档的 UID?
add()
method returns "a Promise resolved with a DocumentReference
指向新建文档写入后台后。
所以,下面应该可以解决问题:
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);
});