Leveraging Object.assign for updating fields in Firebase documents

Currently, I am working on a website that allows users to create new projects by filling out a form with all the necessary project information. Within this form, there is a file input field where users can upload images and documents. I have successfully implemented code that loops through all the files and stores them in Firebase Storage. However, I am encountering an issue when trying to populate the document fields with this data.

I attempted to solve this problem by using Object.assign() within the Firebase .update() method. Unfortunately, whenever this code snippet runs, it throws the following error:

Error: Function DocumentReference.update() called with invalid data. Unsupported field value: a custom File object (found in field image)

After some investigation, I realized that the issue lies with the Object.assign() function as the code works fine without it. If anyone could provide assistance in resolving this issue, I would greatly appreciate it.

The part of the code causing the error is as follows:

firestore.collection('projects').doc(res.id)
    .update(Object.assign(this.values, {
        createdAt: new Date(),
        updatedAt: new Date(),
        createdBy: '/users/' + firebaseApp.auth().currentUser.email,
        approved: false
    }))
    .then(res => {
       console.log(res)
       this.$toast.success('Project changes saved', { icon: 'mdi-check-bold' })
     }).catch((err) => {
         this.$toast.error(err.message, { icon: 'mdi-alert-circle' })
         console.log(err)
       })

Below is the function that I call upon submission:

submit () {
  this.overlay = true

      firestore.collection('projects').add({})
          .then((res) => {
            Promise.all(
              fileKeys.map((key, index) => {
                return new Promise((resolve, reject) => {
                  if (!this.values[key]) {
                    resolve(this.values[key])
                  } else {
                    // Handling file uploads
                  }
                })
              })
            )
            firestore.collection('projects').doc(res.id).update(Object.assign(this.values, { createdAt: new Date(), updatedAt: new Date(), createdBy: '/users/' + firebaseApp.auth().currentUser.email, approved: false }))
              .then(res => {
              console.log(res)
              this.$toast.success('Project changes saved', { icon: 'mdi-check-bold' })
            }).catch((err) => {
              this.$toast.error(err.message, { icon: 'mdi-alert-circle' })
              console.log(err)
            })
          }).catch((err) => {
            console.log(err)
            console.log('error')
          })
        },

Answer №1

The issue here is that the error message is indicating that the object passed to update() includes a File object, which is not compatible. Firestore only accepts objects with common JavaScript types, Timestamps, or DocumentReferences.

This suggests that there may be at least one File object in this.values before calling Object.assign(). It's hard to decipher the code completely, but to resolve this, ensure that you're creating an object without any File objects. Uploading files directly to Cloud Firestore isn't recommended either due to the potential to exceed the maximum document size of 1MB.

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

Implementing pagination in a table with the help of jQuery

I've been working on this code for the past few days and I'm struggling to find a solution that meets my requirements. What I need is pagination within a specific section of a table, with the following actions/events: When clicking previous o ...

The Navigation Bar in Vue Component Renders Incorrectly due to Bootstrap Integration

I am facing an issue with my Bootstrap navbar not displaying correctly within my Vue component. It is appearing as a stacked greyed out button, almost like it's assuming it's on a small device. https://i.sstatic.net/yoPvO.png You can find the c ...

What is the method for retrieving the name of the currently selected HTML element?

After using jQuery to select certain tags, I am now trying to obtain the name of each tag: $('select, :checkbox, :radio').each(function(){ // ... }); To accomplish this, I have attempted the following code: $('select, :checkbox, :radio ...

Oops! The Route.post() function is looking for a callback function, but instead, it received an [object Object

Looking to integrate a password reset feature in my web app, but encountering the error mentioned in the title. Here's a snippet of my code: main.js: const router = express.Router(); const AsyncNewPassword = require('./controller/asyncnewpasswor ...

Is there a way to verify the existence of a specific error in the console?

There seems to be a conflict between a WordPress plugin or code left behind by the previous programmer, causing the WordPress admin bar to always remain visible. While no error is triggered for admins, visitors may encounter a console error. My goal is to ...

Screen the $http request information prior to transmission

Angular has a built-in feature that removes properties with a prefix of $$ from request data or params objects. I want to filter out my own UI-specific properties that I don't want to send to the server, but I don't want to rely on using $$. Is ...

Utilize React Redux to send state as properties to a component

When my React Redux application's main page is loaded, I aim to retrieve data from an API and present it to the user. The data is fetched through an action which updates the state. However, I am unable to see the state as a prop of the component. It s ...

"Encountering an issue with Next.js where the Redux

Hey there, I'm working on a simple project using Nextjs. I need to access the state of my Redux store but I'm encountering an error when trying to use store.getState, it's throwing an error saying getState is undefined. Additionally, I have ...

Problem encountered when closing a lightbox on ASP.net using C# during page load

Can you explain the events that are triggered when the ASP.NET page load event occurs? I am currently using a lightbox for some insertion tasks, and after the insertion is complete, I want the parent page to reload with the new value displayed in the gri ...

Execute the Angular filter again when there is a change in the scope

I am currently working on an application where Users have the ability to switch between kilometers and miles for unit distances. To handle this, I created a custom filter that converts the distances accordingly: app.filter('distance', function() ...

Pause page scrolling temporarily in JavaScript while allowing the scrollbar to continue scrolling until the pause is lifted

I'm currently working on achieving a similar effect to the one found on this website: . On that site, as you scroll down, the 'HELLO' text moves to the side. I've managed to do that part successfully, but I'm facing an obstacle reg ...

Establish a value for the attribute of an HTML tag

Can anyone assist me with setting the attribute value for the following HTML tag using Selenium WebDriver? For example, I need to change 50% to 70% either via JavaScript with WebDriver or a simple WebDriver script. I have tried several options but this pa ...

Load an XML file from the local server asynchronously on the Chrome web browser

Attempting to load a local XML/XSL file into a variable for editing seems to be causing an issue. The code provided functions properly in IE and Chrome, however, Chrome displays a warning due to the synchronous nature of the call. function loadXMLDoc(fileN ...

Adding over 20,000 rows to a table can be time-consuming, causing the page to become unresponsive once the process is complete

Looking at my table structure, it appears as follows: <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{f ...

Unable to transform object into a primitive value using imported JSON data

https://i.sstatic.net/HcY5M.png I am currently working on creating a Vuetify component dynamically within a Nuxt project, as discussed in this Stack Overflow thread (Using different text values with Vuetify component). To achieve this, I am importing and ...

Can ReactJS and jQuery be used together or are they mutually exclusive?

As a beginner in the world of ReactJS, I am intrigued by how this library essentially handles all DOM node rendering without any need for interference from other libraries like jQuery. However, this does pose a challenge as many convenient jQuery plugins ...

Adjust the hue as you scroll

I've been searching for a solution to this issue, but I haven't been able to make it work. My goal is to have the page header change from a transparent background to a red background as the user starts scrolling down the page. $(window).on("s ...

Working with Java to parse non-strict JSON data that does not have keys enclosed in quotes

I am currently facing the challenge of parsing a string in JSON format where keys are not enclosed in quotes. While I have successfully parsed this string in Javascript, I am struggling to find a Java API that can assist me with parsing. The APIs I have at ...

What is causing the navbar to malfunction on mobile devices?

I am facing an issue with my bootstrap navbar. It seems to be getting stuck when the screen resizes or when viewed on a mobile device. I have tried several solutions from various sources, but none seem to work. Here are some of the answers that I have look ...

Deliver transcluded data to the descendant element of a hierarchical roster

I understand that there have been similar questions asked before, but my situation is slightly different. I am currently constructing a nested list and I want to include custom HTML content in each grandchild element alongside some common HTML. The problem ...