1

Currently, I try to update the value of an item in an array with angularfire2. Unfortunately, I only can archive to add an item to the array with arrayUnion and delete it with arrayRemove.

Here is my code:

  // here I try to update the value
  async createAddress(formValue) {
    const arrayUnion = firebase.firestore.FieldValue.arrayUnion;
    await this.db.collection('some-collection')
      .doc('docId'))
      .update({addresses: arrayUnion(formValue)}
      );
  }

  // here I get all items from the array currently stored in
  this.addresses = this.afs.collection('collection')
    .doc<AppUser>('docId')
    .valueChanges()
    .pipe(map(doc => {
        return doc.addresses;
    }));

When I try to delete it first and add it again, the deletion gets skipped and the item is still in the array ...

  arrayUnion = firebase.firestore.FieldValue.arrayUnion;
  arrayRemove = firebase.firestore.FieldValue.arrayRemove;
  docRef = this.db.collection('some-collection').doc('docId'));

  async updateAddress(formValue) {
    await this.docRef.update({
      addresses: this.arrayRemove(formValue)
    }).then( () => {
       this.docRef.update({
        addresses: this.arrayUnion(formValue)
      });
    });
  }

Does anyone know how to solve this? Is there a common workaround? Like, delete it before you save it so that the new one gets added to the array? Or copy the entire array? If so it would be great if anyone could link to an example. Thanks!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
FabianRinortner
  • 103
  • 1
  • 8
  • 1
    There is no way to update an item in an array by its index. You'll need to: 1) read the document, 2) find the item in the array and update it, 3) write the entire array back to the database. See https://stackoverflow.com/questions/46757614/how-to-update-an-array-of-objects-with-firestore – Frank van Puffelen Oct 19 '20 at 15:16

0 Answers0