Firestore - arrayRemove and arrayUnion at same time?

Viewed 210

I want to do something like this.

return await this.fooCol.doc(id).update({
  images: firebase.default.firestore.FieldValue
    .arrayRemove(...data.removedImages).arrayUnion(...data.addedImages),
}); //doesnt work

I'm current doing this where I use Promise.all()

return await Promise.all([
  this.fooCol.doc(id).update({
    images: firebase.default.firestore.FieldValue.arrayRemove(
      ...data.removedImages
    ),
  }),
  this.fooCol.doc(id).update({
    images: firebase.default.firestore.FieldValue.arrayUnion(...imageUrls),
  }),
]);

But is there any other way than using Promise.all()?

1 Answers

If you don't want to pull down the whole array and construct a new one, then it's safest to do this in a batch of 2 operations. Using Web SDK v9 syntax:

const batch = writeBatch(db);
batch.update(doc(db, 'path'), {images: arrayRemove(...data.removedImages)});
batch.update(doc(db, 'path'), {images: arrayUnion(...imageUrls)});
await batch.commit();
Related