Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore - arrayRemove and arrayUnion at same time?

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()?

like image 346
ibrahimxcool Avatar asked Sep 22 '26 17:09

ibrahimxcool


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();
like image 52
Johnny Oshika Avatar answered Sep 26 '26 06:09

Johnny Oshika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!