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

Is it possible to maintain variables across a session with numerous users when utilizing socket.io?

My code structure is designed as follows: //Route Handler that triggers when a user 'creates a session' app.post('/route', async (req, res) => { let var1 = []; let var2 = []; io.on('connection', (socket) => ...

When initializing a Vue application using the command 'vue create hello-world', the './fs' module is not found

After spending the last 3-4 hours trying to work with Vue, I'm finding it incredibly challenging just to get it up and running. I've been following the documentation provided here: https://cli.vuejs.org/guide/creating-a-project.html#vue-create ...

Discovering descendant div elements

I've been conducting some research, but I'm struggling to find a specific answer for this. Here is the HTML code snippet: <div class="collapsingHeader"> <div class="listItemWrapper"> <div class="itemWrapper"> ...

Having trouble executing "npm install" following the clone from GitHub in React

After cloning a repository from GitHub, I attempted to run "npm install" but encountered the following error: Since the project is still in development, should I install or add anything else to successfully run it? ...

"Learn how to pass around shared state among reducers in React using hooks, all without the need for Redux

I've built a React hooks application in TypeScript that utilizes multiple reducers and the context API. My goal is to maintain a single error state across all reducers which can be managed through the errorReducer. The issue arises when I try to upd ...

Is there a method to track the progress of webpage loading?

I am working on a website built with static HTML pages. My goal is to implement a full-screen loading status complete with a progress bar that indicates the page's load progress, including all images and external assets. Once the page has fully loaded ...

When utilizing a script to deliver a true or false response for jQuery's .load() function

Currently, I have found myself delving deep into jquery to manage the ajax requests in my web applications. Specifically, I am working on a bidding system in PHP that heavily relies on mod_rewrite. Using jQuery with a confirm dialog, I send an Ajax request ...

Setting a menu item as active in a SvelteKit app: A step-by-step guide

I encountered an issue with the main navigation menu in my sveltekit application. The problem is that when the app is loaded or refreshed, the active menu item corresponding to the current URL is not set. After struggling to find a solution online, I manag ...

Combine and emphasize several gridview rows into a single highlighted unit

Imagine you have a gridview that looks like this: FAMILY GROUP COLOR =============================================== | | Poodle | Blue ROW1 | DOG | German Shepherd | Red | | Pitbul ...

Combining PHP Variable with URL String

<td><input type="submit" onClick="window.location.href='https://www.'.$myValue.'.test.com'" value="Click!"></td> I am trying to create a button that will redirect to one of eight possible URLs based on a variable. How ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

Rendering a component and updating state with inline onClick event handlers

When discussing the concept of pure render methods in React and highlighting the serious anti-pattern of setting state inside the render function, how strictly should this be adhered to? It is understood that triggering a setState within the render functio ...

The drop-down menu does not maintain its selected option after the window is refreshed

I am struggling with a dropdown list as shown below: <select class="span2" id ="sort" name= "order_by"> <option >Default</option> <option >Price</option> <option >Color</option> ...

Encountering NPM install gyp errors in VSCode indicating that gyp is searching for Visual Studio

Running npm install on a local project has been quite challenging for me, as I keep encountering errors every time I try. Fortunately, some valuable information I found related to gyp and Python helped me make some progress. However, I'm currently fac ...

Initiate the function one time

The Introduction: I need assistance with a form that triggers a jQuery function when a button is clicked. The issue arises after the initial execution, as the function continues to run one more time. My dilemma is figuring out how to ensure that the funct ...

Using AngularJS to auto-populate additional fields after selecting an option from the typeahead autocomplete feature

Just starting with AngularJS and finally figured out how to implement Auto-complete in Angularjs. Now, when a user selects a value from the auto-complete, I want other fields to be populated based on that selection. For example, upon loading the screen, d ...

Updating the content of a list item on the fly using React

After spending all day on this, I am feeling a bit frazzled. Trying to achieve what would take 20 seconds in JQuery has proven to be quite the challenge in React ¯\_(ツ)_/¯ In my application, tags are ranked by importance from 1 to 9. Simple enoug ...

Utilizing NodeJS to Refine JSON Data

I am working with a JSON array that consists of multiple objects. My goal is to retrieve objects that have a specific value, such as returning [ service_wog: { count: 48, popular: false, code: 33, price: 20, id: ...

Is it feasible to obtain multiple tag-name indexes using JavaScript?

Exploring the table search function provided by W3Schools has brought up an interesting question in my mind. Is it feasible to simultaneously retrieve multiple indexes using getElementsByTagName and conduct a search across the entire table instead of just ...

Skip nodes in Polymer 1.0 by using ExcludeLocalNames

I recently attempted to transition from Polymer version 0.5 to 1.0 and came across a particular question: Is there a way to exclude certain nodes inside a paper-menu? In the previous version (0.5), you could use the attribute excludedLocalNames to achieve ...