【问题标题】:Javascript: cannot store array of objects to FirestoreJavascript:无法将对象数组存储到 Firestore
【发布时间】:2022-02-11 08:03:24
【问题描述】:

我正在尝试将对象存储到 Firestore。 我的对象包含一个数组:

{
  returnMode: false,
  id: "SE-74c5219a-acfe-4185-9e33-f78b10ac3f1e",
  prices: [
    {
      price: {
        twoHours: 0,
        firstHour: 0,
        id: "zero",
        unlock: 0,
        final: 0,
      },
      permission: { id: "GENERAL" },
    },
    {
      price: {
        twoHours: 150,
        unlock: 100,
        id: "oebb_low",
        firstHour: 50,
        final: 50,
      },
      permission: { id: "OEBB" },
    },
  ],
}

如果这个对象被硬编码到云函数中,它可以让我将它保存到 Firestore 而不会失败。如果我用类似这样的变量替换上述对象的数组,它仍然有效:

const array = [
    {
      price: {
        twoHours: 0,
        firstHour: 0,
        id: "zero",
        unlock: 0,
        final: 0,
      },
      permission: { id: "GENERAL" },
    },
    {
      price: {
        twoHours: 150,
        unlock: 100,
        id: "oebb_low",
        firstHour: 50,
        final: 50,
      },
      permission: { id: "OEBB" },
    },
  ];
{
  returnMode: false,
  id: "SE-74c5219a-acfe-4185-9e33-f78b10ac3f1e",
  prices: array,
}

但是,当上述数组没有硬编码到 Cloud Function 中而是由我的程序创建时,它会失败。这是生成数组的代码:

const bikeBoxPriceArray = [];

for (let i = 0; i < bikeBoxPermissionArray.length; i += 1) {
  const doc = bikeBoxPermissionArray[i];
  // I cut out the stuff that is not important

  const bikeBoxPriceArrayElement = {
    permission: {
      id: doc.id,
      name: doc.name,
    },
    price: {
      id: priceId,
      unlock: priceUnlock,
      firstHour: priceFirstHour,
      twoHours: priceTwoHours,
      final: priceFinal,
    },
  };

  bikeBoxPriceArray.push(bikeBoxPriceArrayElement);
}

我通过bikeBoxPriceArray instanceof Array 验证它确实是一个数组。我究竟做错了什么?我尝试了很多很多东西,但我就是想不通。为什么在硬编码时它可以工作但对变量不起作用?

代码在 Firebase 事务中,没有错误消息,它只是告诉我错误的位置。

【问题讨论】:

  • 您能否提供额外的代码,以便任何人都可以使用它来尝试重现您的错误?此外,请附上您遇到的错误消息以供其他参考。
  • @RJC 我已经解决了这个问题,除了交易失败之外我没有收到错误消息。我回答了自己的问题以解释我是如何解决的。这个问题很奇怪,我相信我的回答可以帮助一些有类似问题的人。

标签: javascript arrays json google-cloud-firestore


【解决方案1】:

我从this post 找到了我自己问题的答案。

在将对象与数组合并之前,需要对数组进行字符串化,然后像这样再次解析:

const array = JSON.parse(JSON.stringify(bikeBoxPriceArray));

const sessionDocObj = {
  returnMode: false,
  timestamp: {
    // sessionCreated: admin.firestore.FieldValue.serverTimestamp(),
    sessionCreated: "Karoline",
  },
  id: "SE-" + uuidv4(),
  prices: array,
};

【讨论】:

    猜你喜欢
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    相关资源
    最近更新 更多