简体   繁体   English

如何使用 arrayUnion (TypeScript) 将字符串数组 append 转换为 Firebase 中的数组

[英]How to append an array of strings to an array in Firebase using arrayUnion (TypeScript)

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.我正在尝试在 TypeScript 中编写的 Firebase Cloud Function 中使用 arrayUnion。每当我添加数组时,它也会添加变量“items”的名称。 Not sure why this is or what I'm doing wrong.不知道为什么会这样或我做错了什么。

Picture of my database after appending 2 strings (This is obviously wrong):附加 2 个字符串后我的数据库的图片(这显然是错误的):

IMAGE - 运行云功能后的 firebase 数据库

My goal is to add a list of strings to my database.我的目标是将字符串列表添加到我的数据库中。 There should not be any duplicate ids in the unioned array.联合数组中不应有任何重复的 id。

What I've Tried我试过的

Firbase Function is called sucesfully with Array items = ['00000000000009', '00000000000008'] Firbase Function 被成功调用 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 输出

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:从日志 output 看来,您的items是一个包含items子数组的object ,因此您需要在将其传递给 Firestore 之前将其解包:

await this.firestore.collection("users").doc(uid).update({   // 👇
  wishlistedItems: admin.firestore.FieldValue.arrayUnion(items.items),
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM