将一个对象数组推送到Firebase Collection Angular 8中。

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

我试图在我的用户集合中添加一个文档到一个数组 studyList 中。

所以我有一个用户集合,其中我有名字等......和studyList.当我点击按钮买入一个DocumentItemComponent时,我想把这个文档添加到这个StudyList数组中。

enter image description here

当我点击一个按钮买入一个DocumentItemComponent时,我想将该文档添加到这个StudyList数组中。

我的代码部分工作,因为它将文档添加到数组中,但当我点击另一个文档时,它改变了第一个文档,它没有添加另一个文档。

这是我添加函数的代码。


   addToStudyList(user) {
        const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.id}`);
        const data: UserInterface = {
          studyList: [{
            title: this.document.title,
            language: this.document.language,
            description: this.document.description,
            cover: this.document.cover,
            category: this.document.category,
            field: this.document.field,
            id: this.document.id,
            author: this.document.userUid,
            urlDocument: this.document.urlDocument
          }]

        }
        return userRef.set(data, {merge: true});

   }

你能帮帮我吗,谢谢!谢谢!祝你有个愉快的一天

arrays angular firebase collections push
2个回答
1
投票

这是因为当你在这段代码中声明:

  studyList: [{
            title: this.document.title,
            language: this.document.language,
            description: this.document.description,
            cover: this.document.cover,
            category: this.document.category,
            field: this.document.field,
            id: this.document.id,
            author: this.document.userUid,
            urlDocument: this.document.urlDocument
          }]

在这段代码中,你只给 studyList 数组分配了一个对象,这将覆盖现有的数组,相反,你应该利用现有的用户 studyList 数组,并将你的新对象推入其中,就像这样。

  addToStudyList(user) {
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.id}`);
    user.studyList.push({
        title: this.document.title,
        language: this.document.language,
        description: this.document.description,
        cover: this.document.cover,
        category: this.document.category,
        field: this.document.field,
        id: this.document.id,
        author: this.document.userUid,
        urlDocument: this.document.urlDocument
      });
    const data: UserInterface = {
      studyList: user.studyList

    }
    return userRef.update(data);

}


1
投票

在文档中没有直接更新数组的方法,但如果你使用Firestore,它提供了arrayUnion和arrayRemove函数,你可以使用这些函数在数组中添加和删除唯一的项目。

从firestore文档中可以看出,它提供了arrayUnion和arrayRemove两个函数,可以用来在数组中添加和删除唯一的项目。https:/firebase.google.comdocsfirestoremanag-dataadd-data#update_elements_in_an_array。 :

试试这个。

userRef.update({
  studyList: firebase.firestore.FieldValue.arrayUnion(data)
});
© www.soinside.com 2019 - 2024. All rights reserved.