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