Home > Software design >  How to append an array of strings to an array in Firebase using arrayUnion (TypeScript)
How to append an array of strings to an array in Firebase using arrayUnion (TypeScript)

Time:12-11

I am trying to use arrayUnion inside of a Firebase Cloud Function written in TypeScript. Whenever I add the array tho it adds the name of the variable "items" as well. Not sure why this is or what I'm doing wrong.

Picture of my database after appending 2 strings (This is obviously wrong):

IMAGE - firebase database after running cloud function

My goal is to add a list of strings to my database. There should not be any duplicate ids in the unioned array.

What I've Tried

Firbase Function is called sucesfully with Array items = ['00000000000009', '00000000000008']

//Defined in class constructor
private firestore: FirebaseFirestore.Firestore


async addItemsToWishlist(uid: string, items: string[]): Promise<boolean> {
    try {
      // Nothing Added Function called for no reason
      if (items.length == 0) {
        return true;
      }

      console.log("Called Successfull with items: ", items);
      console.log("items length: ", items.length);

      // Add the items to the corresponding users Wishlist
      await this.firestore.collection("users").doc(uid).update({
        wishlistedItems: admin.firestore.FieldValue.arrayUnion(items),
      });

      // Return true if successful
      return true;
    } catch (e) {
      // Log the Error on the Console
      console.error(e);
      return false;
    }
}

Also not sure why i cant get the length of my array if items. Console logs:

IMAGE - Console.log output

CodePudding user response:

From the log output it looks like your items is an object that contains an items child array, so you need to unwrap that before passing it to Firestore:

await this.firestore.collection("users").doc(uid).update({   //            
  • Related