将字段属性添加到Firebase中的文档中

问题描述 投票:0回答:1

每次单击按钮添加时,我都会调用一个方法。在这种方法中,我为集合创建了一个新文档,其中包含标题和字符串数组。通过从保存的服务中调用一个方法,可以在我的方法中完成此文档的创建。单击完成按钮时,我想向文档中添加最后一个字符串值字段。我如何获取当前已保存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)

}

此方法是saveService的一部分

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

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

   this.db.collection('saved').add(savedFields);
}
javascript angular firebase google-cloud-firestore
1个回答
1
投票

据此(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

© www.soinside.com 2019 - 2024. All rights reserved.