Storing an array of objects in Firestore using JavaScript presents a challenge

I am attempting to save an object to Firestore which includes an array:

{
  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" },
    },
  ],
}

When I hard-code this object into the Cloud Function, it successfully saves to Firestore without any issues. However, if I replace the array in the object with a variable like this, it continues to work:

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,
}

However, when the array is dynamically generated by my program rather than hard-coded, it fails to save. The following code snippet shows how the array is created:

const bikeBoxPriceArray = [];

for (let i = 0; i < bikeBoxPermissionArray.length; i += 1) {
  const doc = bikeBoxPermissionArray[i];
  
  const bikeBoxPriceArrayElement = {
    permission: {
      id: doc.id,
      name: doc.name,
    },
    price: {
      id: priceId,
      unlock: priceUnlock,
      firstHour: priceFirstHour,
      twoHours: priceTwoHours,
      final: priceFinal,
    },
  };

  bikeBoxPriceArray.push(bikeBoxPriceArrayElement);
}

I have confirmed using

bikeBoxPriceArray instanceof Array
that it is indeed an array. What could be causing this issue? I have tried various solutions but cannot seem to identify the problem. Why does it work when hard-coded but not with a variable?

This code is executed within a Firebase Transaction and no error message is displayed, just the location of the error.

Answer №1

After some research, I came across a solution to my own question in this helpful post.

To successfully merge the object with the array, it is important to stringify the array first and then parse it again as shown below:

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The array of type __NSArrayM was modified during enumeration

Application Specific Information: *** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x17204b070> was mutated while being enumerated.' ...

Progressive Web App with Vue.js and WordPress Rest API integration

When creating an ecommerce website using Wordpress, I utilized Python for scraping data from other websites to compare prices and bulk upload products through a CSV file. My next goal is to learn Vue and transform the website into a PWA as it will be esse ...

Error in Laravel npm package

Working on my Laravel project, I encountered an issue while trying to implement a video chat feature using https://github.com/PHPJunior/laravel-video-chat?ref=madewithlaravel.com with laravel-echo-server. Despite trying various solutions, none seemed to wo ...

When utilizing an object as state in React, the `setState` function will only set

Currently, I am working on developing a React form that utilizes a custom Input component which I have created multiple times. The objective is to gather all the names and values from the form in the parent component: {inputName: value, inputName2: valu ...

JavaScript code to transform a string into a JSON array

I utilized s3 select to extract specific data for display on my frontend. I converted an array of bytes to a buffer and then to a string as shown below: let dataString = Buffer.concat(records).toString('utf8'); The resulting string looked like ...

What is the best way to import the L module from the "leaflet" library in Next.js?

Implementing Leaflet into my Next.js development posed a challenge as it did not support server side rendering (SSR). To address this, I had to import the library with SSR disabled using the following approach: import React, {Component} from "react&qu ...

Converting NodeJS newline delimited strings into an array of objects

What is the method for reading a text file as follows: `{'values': [0,1,0], 'key': 0} {'values': [1,1,0], 'key': 1} {'values': [1,1,0], 'key': 1}` using: var fs = require('fs'); fs. ...

Accessing Wordpress REST API securely with Xamarin Forms using Username and Password information

Is there a method to access the username and password of a specific user using the Wordpress API? It appears that Wordpress has designated the password field as WRITE-ONLY in their API documentation. Using POSTMAN, I am able to retrieve the user's d ...

Is there a way to automatically change the display of an element once the user has closed the menu?

How can I ensure that the display of an element remains unchanged when a user opens and closes my website menu using JavaScript? ...

Having trouble with rendering prop values in Vue.js?

Struggling to develop an ajax form component in vuejs within a Laravel 5.3 application. It seems I am facing some challenges with displaying the form fields. Can someone lend me a hand? Here is the front end code for rendering the form: <ajax-form ...

Implementing a jQuery method in a PHP page that is loaded through AJAX

I am facing an issue on my page where I am using jquery/ajax to load a series of buttons into a div. This script loads buttons every time the user scrolls the page and each button should run a jquery function when clicked. The problem arises when I switche ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

Inserting an HTML element into Handlebars.js during a specific iteration of an each loop

I have a channel.json file containing 7 objects of data which are iterated in hb. I am looking for a way to insert a date between these iterations without modifying the .json file. How can I add an html tag to display after the 3rd iteration within the loo ...

Issue with Angular controller failing to load when link is clicked

I am currently developing a webpage that incorporates Angular and responds to ajax requests by populating data into a table. When I manually enter the address, everything works as expected. However, if I navigate to the page using a link ( <a href="/pro ...

Verify if a set of Radio buttons contains at least one option selected

Need help with validating a Feedback Form using either JQuery or Javascript. The requirement is to ensure that every group of radio-buttons has one option selected before the form can be submitted. Below is the code snippet from form.html: <form id=&ap ...

transferring a 2D array from C# to unmanaged C++ through a C++/CLI wrapper

I am currently working on a project that requires optimization, and I need to convert a portion of code from C# to C++. I have started using a C++\CLI wrapper, but I am still grappling with this new approach and haven't fully grasped it yet. Unfo ...

Looping through Vue with multiple options

Looking for help with Vue2 looping to display multiple options within a select element. We have an object structured like this; sorting = { name: [ 'asc', 'desc' ], price: [ 'cheapest', ...

Assign local variable in Mongoose using query results

I created a function to query MongoDB for a credential (simplified): var query = Credential.findOne({token: token}); return query.exec(function (err, credential) { if (err) return null; return credential; }); The next step is to use this credent ...

Utilize Angular service to deliver on a promise

Currently, I have a service that is responsible for updating a value on the database. My goal is to update the view scope based on the result of this operation (whether it was successful or not). However, due to the asynchronous nature of the HTTP request ...