首页 > 解决方案 > 如何使用 Angular Fire 从我的 Angular 代码中检索插入到 FireStore 集合中的文档的 UID?

问题描述

我正在开发一个使用 AngularFire 与 FireStore 数据库交互的 Angular 9 项目。

我有这个代码片段可以在我的 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?

标签: angularfirebasegoogle-cloud-firestoreangularfire2

解决方案


add()方法返回“一个 PromiseDocumentReference在写入后端后指向新创建的文档。”

因此,以下应该可以解决问题:

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);
        });

推荐阅读