javascript - 将字段属性添加到 firebase 中的文档

标签 javascript angular firebase google-cloud-firestore

每次单击“添加”按钮时,我都会调用一个方法。在此方法中,我为我的集合创建一个新文档,其中包含标题和字符串数组。该文档的创建是通过调用我保存的服务中的方法在我的方法中完成的。我想在单击完成按钮时将最后一个字符串值字段添加到我的文档中。如何获取当前保存的 id 的快照以便添加新元素? 我正在使用 Angular 和 firestore

这些按钮位于 component.html 中

<button type="button" class="btn btn-success" (click)="onSave()">Save</button>

<button type="button" class="btn btn-success" (click)="onComplete()">Complete</button>

OnSave 和 onComplete 位于 component.ts 中

onSave() {

    const btn = document.getElementById("addtopic");
    this.modalService.hide(1);

    // Get starting date
    this.startTopicTimestamp=  firebase.firestore.Timestamp.fromDate(new Date());
    console.log(`Starting time : ${this.startTopicTimestamp}`);

    btn.innerHTML = "End topic";
    btn.setAttribute('class', 'btn btn-danger');

    // New document creation
    this.savedService.savedDoc(this.topicTitle, this.myTags, this.startTopicTimestamp);
}


onComplete(){

    // Here we should get a snapshot of the current saved id
    // To make this function work
    this.savedService.addElement(this.saved.id)

}

此方法是savedService的一部分

public savedDoc(title: string, tags: string[], date: Date): void {

    const savedFields = {
      title: title,
      startTime: date,
      tags: tags
    }

   this.db.collection('saved').add(savedFields);
}

最佳答案

根据这个( Firestore - How to get document id after adding a document to a collection ),你可以这样做:

public savedDoc(title: string, tags: string[], date: Date): void {

    const savedFields = {
      title: title,
      startTime: date,
      tags: tags
    }

   return this.db.collection('saved').add(savedFields).then(function(docRef) {
    return docRef.id;

});
}

因为add返回一个DocumentReference

关于javascript - 将字段属性添加到 firebase 中的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58731609/

相关文章:

css - 如何在 Angular 11.2.0 或更低版本中设置 TailwindCSS

javascript - 从 rxjs 存储中的状态获取最新的 2 个值

Angular 6如何通过管道进行http调用

java - 从 Firebase 存储中获取随机图像

angular - Firebase 可以直接连接到 Angular 而无需任何中间层吗?

JavaScript 对象创建和函数调用步骤

javascript - 尝试在我的网络应用程序中测试 google oauth 时出现 popup_closed_by_user 错误

在显示控制台之前,IE 中未定义的 Javascript 变量

javascript - Express 中的多个静态资源目录

android - Firebase 持久性模式从不同步到服务器 (Android)