如何使用Angular Firestore创建和更新子集合?

时间:2018-04-18 11:50:37

标签: javascript angular google-cloud-firestore angularfire2

我在Firestore中创建了一个Collection“Person”。我可以从代码中创建文档和字段。

ngOnInit() {
this.personCol = this.afs.collection('person');
//snapshotChanges is used to retreive the document data and other metadata, which includes the ID
//we need ID to edit or delete a record
this.person = this.personCol.snapshotChanges()
  .map(actions => {
   return actions.map(a => {
     const data = a.payload.doc.data() as Person;
     const id = a.payload.doc.id;
     return { id, data };
   });
  });}
addPerson() {
this.afs.collection('person').add({
  'name': this.name,
  'age': this.age,
});}
getPerson(PersonId) {
this.personDoc = this.afs.doc('person/'+personId);
this.singlePerson = this.personDoc.valueChanges();

}

现在我想添加一个人借书的清单:

Person: 
{Name: "John"
 Age: 32 
 Books: {Title: "First book", Author: "Some author"
         Title: "Second book" Author: "Another author"},
{Name: "Anne"
 Age: 21
 Books: {Title: "How to... book", Author: "Author Name"
         Title: "Flowers book" Author: "Another author"} 

如何使用Angular创建Books子集合? 如何访问Books子集以更新代码中的titleauthor

2 个答案:

答案 0 :(得分:2)

要访问特定人员的书籍子集:

this.personBooks = this.afs.collection('person/'+personId+'/Books');

答案 1 :(得分:0)

好的,感谢Frank van Puffelen,我找到了一个添加子集的解决方案。首先,我要创建一个人并显示所有人的列表。

addPerson() {
 this.afs.collection('person').add({
  'name': this.name,
  'age': this.age
  });
}

当我点击列表中的一个人时,我会获得personId,然后我会在books子集合中添加图书:

addBook(personId) {
 this.afs.collection('person/' + personId + '/books').add({
  'book': this.book
 });
}

如果在此之前创建了books,则会将该书添加到该集合中,如果不是,则首先创建books子集并添加第一本书。