The updateDoc function does not allow for using a variable as a field name

I am currently using the updateDoc function from Firestore and VueJs as my framework. I am attempting to create a nested document with the user input (member_name) as a field name. However, I am encountering an error stating "Unexpected keyword 'this'. (42:20)". The issue seems to be coming from this specific section.

this.member_name: {
      name: this.member_name,
      task: 0,
      task_status: 0,
}

Could you assist me in resolving this issue? Below is the complete code snippet for reference.

<template>
    <div class="container shadow m-3 col-12">
    <div class="d-flex justify-content-center m-2">
        <h1>Add Member</h1>
    </div>
    <label for="member_name">Member name</label>
    <input class="form-control m-1" type="text" id="member_name" v-model="member_name"/>       
    <label for="member_email">Member Email</label>
    <input class="form-control m-1" type="email" id="member_email" v-model="member_email"/>       
    <div class="d-flex justify-content-center">
        <button @click.prevent="submit" class="btn btn-primary col-6 m-2">Submit</button>
    </div>
    </div>   
</template>

<script>
import firebaseApp from '@/firebase.js'
import { getFirestore } from "firebase/firestore"
import { doc, updateDoc} from "firebase/firestore"
const db = getFirestore(firebaseApp);

import { getAuth, onAuthStateChanged } from "firebase/auth";

export default {
    name: "AddMember", 
    components: {
        
    }, 
    data(){
        return{
            email:"",
            project_name:"",
            member_name:"",
            member_email:"",
        }
    },

    mounted(){
        const auth = getAuth();
        onAuthStateChanged(auth, (user) => {
        if (user) {
            this.email = user.email
            console.log(this.email)
        } else {
            console.log("Sorry")
        }
        });
    },

    methods: {
        async submit() {
            alert("Add new member successfully!")
            this.project_name = this.$route.query.project_name
            const projectDoc = doc(db, "projects", this.project_name);
            await updateDoc(projectDoc, {
                member_list: {
                    this.member_name: {
                        name: this.member_name,
                        task: 0,
                        task_status: 0,
                    }  
                },
            });
        }
    },
}
</script>

<style>

</style>

Answer №1

To reference the variable value as a property name, you can utilize the `[]` notation:

await updateDoc(projectDoc, {
    member_list: {
        [this.member_name]: { // 👈
            name: this.member_name,
            task: 0,
            task_status: 0,
        }  
    },
});

Additionally, if you wish to include the member in the existing `member_list` array, you should make use of the `array-union` operator explained in the documentation on updating elements in an array field.

Answer №2

When working with the document, it is important to set the correct value. Take a look at this code snippet:

await updateDoc(projectDoc, {
    member_list: {
        this.member_name: {
            name: this.member_name,
            task: 0,
            task_status: 0,
        }  
    },
});

The issue lies in the third line where the structure of the object should be declared, not referenced as a value.

To correct this, you should structure it as follows:

await updateDoc(projectDoc, {
    member_list: {
        member_name: {
            name: this.member_name,
            task: 0,
            task_status: 0,
        }  
    },
});

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

I encountered a validation error and a 404 error while trying to input data into all fields. Kindly review and check for accuracy. Additionally, I have included an

click here for image description Despite providing all details in the form fields, I keep receiving an error message prompting me to enter all fields... I am also encountering a "/api/user 404 Not Found" error and unsure of the reason. Interestingly, wh ...

What is the best way to transfer a file to a server using a node library, like axios for instance

When using the CURL command to upload a file to a server, I have encountered an issue with a few CLIs. It seems that only CLIs with CURL installed are working fine when running my node app. let filesPath = `http://abc/api/789012/files-api`; exec(`curl - ...

Php/JavaScript Error: Identifier Not Found

I've double-checked my code multiple times, but it still doesn't seem to be working properly. When the PHP runs, the browser console displays the following error: Uncaught SyntaxError: Unexpected identifier. I'm not sure if this is a si ...

The issue of JQuery Mobile not recognizing HREF links when combined with Javascript

I am facing a challenge with my button functionality that is supposed to open a panel. However, there seems to be an interference caused by my JavaScript code. The panel contains a notifications center and in order to retrieve the notifications, I have to ...

issue with deploying a software package and getting it installed

I developed a basic package containing only a simple <div> x </div> and published it using npm publish. When I attempted to install it in a project using npm i, I encountered the following error message: Support for the experimental syntax &apo ...

Error encountered when attempting to retrieve HTML content from localhost using AJAX

Attempting to insert HTML code into a div element using ajax, similar to how it's done with an iframe. Testing this out locally first to avoid Same Origin Policy complications. The web application is currently hosted on a wamp server. There are two ...

Add HTML content to a specific div according to the option selected in a drop-down menu

I am currently working on a project where I need a button to insert HTML content into a div based on the value selected in a select box. However, the functionality is not working as intended. Upon clicking the button, nothing happens. I am unsure of what t ...

What is the best way to choose the unique identifier of an HTML element inside a for loop in a Django template?

I need help selecting an HTML button that is generated within a for loop in a Django template using JavaScript. How can I assign a unique ID to each button and select it correctly in JavaScript? Currently, all buttons have the same ID within the loop, resu ...

I have image paths stored in my mySQL Database, how can I showcase them on my website?

As a beginner, I'm embarking on a learning journey where my aim is to showcase images from my database alongside other content within the same row in my HTML. Below is the JavaScript code snippet from my HTML file: <script type="text/javascri ...

Having trouble getting the ReactJS AXIOS post function to work properly?

Error in console: [1]: https://i.sstatic.net/xOfUV.png issue with axios request .post("https://bootcamp-2022.devtest.ge/api/application", { token: "7e475dfc-0daa-4108-81c8-d6c62a3df4ca", first_name: JSON.parse(localStorage.ge ...

Select an item from the options available

Looking to automatically select a specific item from a combobox upon clicking a button on my webpage. The page includes both PHP and JavaScript code for this functionality. Currently, I have a JavaScript function triggered by the "onclick" event of the bu ...

Combining arrays of objects that contain nested arrays of objects using JavaScript along with libraries such as lodash or Underscore

Attempting to combine two arrays of objects using the lodash JavaScript library, however, encountering an issue where the Subcategories property containing another array is not being merged. Here are the arrays to be combined: var menu1 = [ { "PageNa ...

Updating the text of an element will occur only when the specified condition has been met

I am trying to dynamically change the text within the <span data-testid="recapItemPrice">ZADARMO</span> element from 'ZADARMO' to 'DOHODOU' only when the text inside the parent element 'INDIVIDUÁLNA CENA PREP ...

A step-by-step guide on including an object within an object array with Javascript

In the code snippet below, I have a JavaScript object that I'm trying to add a similar object to using request.rules[0]. request : [ rules: [ { pageFilters: [ { matchType: 'contains', type ...

Terminate child process with specified user ID using the Forever-monitor

Whenever I need to create new child node processes, I use the following code: var forever = require('forever-monitor'); function startNodeProcess(envVariables, jsFileName, uid) { var child = new (forever.Monitor)(jsFileName, { ...

Tips for extracting data from a state-based object store in React?

https://i.sstatic.net/A0cc4.pngWhenever I attempt to execute a PUT call, I fetch the data by id and save it in a state named "getData". While I am able to filter and map over this data, I face issues when trying to extract individual values. For instance, ...

Manipulate and scale with jQuery

I am currently utilizing the jQueryUI library with its Draggable and Resizable functionalities to resize and drag a div element. However, I am encountering some unexpected behavior where the div jumps outside of its container upon resizing. How can I resol ...

Tool tips not displaying when the mouse is moved or hovered over

I have customized the code below to create a multi-line chart with tooltips and make the x-axis ordinal. However, the tooltips are not displaying when I hover over the data points, and I want to show the tooltips only for the data in the variable. https:/ ...

When using CSS float:left and overflow:visible, the text may get cropped-off at

I'm currently experimenting with creating a color gradient in javascript using numerical values within some of the divs to indicate scale. However, I've run into an issue where as the values get larger, they are cut off due to the float:left prop ...

Extracting Values from a jQuery Array Object

Good day everyone! Here is the code I am currently working with: var items = []; $(xml).find("Placemark").each(function () { var tmp_latLng = $(this).find("coordinates").text(); tmp_latLng = tmp_latLng.split(","); items.push({ name: ...