javascriptarraysfirebasegoogle-cloud-platformgoogle-cloud-firestore

How to remove a value from an array within a batched write in Firestore?


I am using JavaScript with CDN imports and I am trying to remove an element from an array within a batched write, however, it seems that no matter what I try I keep getting errors with the most common being the following: Uncaught (in promise) TypeError: FieldValue.arrayRemove is not a function

I use the following import for the Firestore:

import { getFirestore, doc, getDoc, writeBatch, FieldValue } from "https://www.gstatic.com/firebasejs/11.0.1/firebase-firestore.js";

I have tried a couple of solutions, and the ones I can remember I have here below (here 'theirUIDsDocRef' is the reference to the document with the array, 'UIDs' is the name of the array, and 'myUID' is a variable containing my UID which I want to delete):

batch.update(theirUIDsDocRef, { "UIDs": FieldValue.arrayRemove(myUID) });

batch.update(theirUIDsDocRef, "UIDs", FieldValue.arrayRemove(myUID));

batch.update(theirUIDsDocRef, { UIDs: FieldValue.arrayRemove(MyUID) });

If there is anything else you might need to know, please ask.


Solution

  • To solve the issue, you need to use the following import:

    import { getFirestore, doc, getDoc, writeBatch, arrayRemove } from "https://www.gstatic.com/firebasejs/11.0.1/firebase-firestore.js";
    //                                                  👆
    

    And then use the first statement but without FieldValue:

    batch.update(theirUIDsDocRef, { "UIDs": arrayRemove(myUID) });
    

    This solution will work only if the myUID matches the UID that exists inside the UIDs array.