I encountered an error while trying to add a document to Firestore using the 'add' method in Vue.js. Can someone provide guidance on how to

Whenever the function is triggered (on click), I aim to include a new document. Although it functions with .set(), my goal is for a new document to be created each time the form is submitted.

The current error code I am encountering is:

I initially suspected there might be an issue with my connection, but everything seems to be in order.

This is my database connection file:

import firebase from 'firebase'
import 'firebase/firestore'

 let config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
  };
  
// Obtain a Firestore instance
export const db = firebase.initializeApp(config).firestore()

My attempts to search for solutions online have been unsuccessful thus far.

AddProduct.vue script section only:

<script>
/*eslint-disable-line*/import { db } from '../Database';
import firebase from 'firebase';

export default {
    firestore: {
        Products: db.collection('Products')
    },
    data() {
        return {
            sort: ['Fruit', 'Vegetable'],
            fruit: ['Apple', 'Bananan', 'Grape', 'Kiwi', 'Lemon', 'Mango', 'Orange', 'Pear', 'Pineapple', 'Strawberry', 'Watermelon'],
            vegetable: ['Cabbage', 'Radish', 'Carrot', 'Parsnip', 'Lettuce', 'Green bean', 'Aubergine', 'Tomato', 'Cucumber', 'Sweet pepper'],
            quality: [1,2,3,4,5,6,7,8,9,10],
            cours: ['€', '$', '£', '₺'],
            random: Math.floor(Math.random() * 1000000),
            addProducts: {
                catogorie: '',
                product: '',
                quality: '',
                availability: '',
                cours: '',
                price: '',
                firstName: '',
                lastName: '',
                companyName: '',
                email: '',
                location: '',
                country: '',
            }
        }
    },
    methods: {
        async add() {
            var currentUser = firebase.auth().currentUser.uid
            const res = await db.collection('Products').doc(currentUser + this.random).add({
                addProducts: this.addProducts
            });
            console.log(res)
        }
    },
    created() {
        console.log(this.random)
    }
}
</script>

I may not be skilled at drawing, but the red blocks are meant to represent new documents generated by the same form with different data attributes.

Answer №1

Your current code is attempting to execute add() on a DocumentReference object:

await db.collection('Products').doc(currentUser + this.random).add({
    addProducts: this.addProducts
});

This is not valid because the DocumentReference does not include a method named "add".

If you intend to create a document using a DocumentReference, you should use the set() method instead.

await db.collection('Products').doc(currentUser + this.random).set({
    addProducts: this.addProducts
});

The add() method belongs to the CollectionReference and it appends a document with a unique random ID. Since you are supplying your own ID, this approach may not be suitable. If you prefer to utilize the randomly generated ID, you can modify the code like so:

await db.collection('Products').add({
    addProducts: this.addProducts
});

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 console is showing an error message stating that the variable "i" is not

Currently, I am developing the dashboard for my discord.js bot. While working on it, I encountered an issue where a variable I created to select an array from my JSON file is being reported as undefined by the console. $(function() { $.getJSON( "./data/ ...

Sending a Boolean value from a child component to its parent state in React JS

Within my application, I have implemented a login feature in the navbar component. However, I am encountering an issue with updating a variable in the main component upon successful login. Although I have successfully managed to set up the login functional ...

Issue with Responsive Font Size functionality in Tailwind and ReactJS not functioning as expected

I'm really struggling with this issue. I grasp the concept of mobile-first design and have successfully made my website's layout responsive. However, I'm having trouble getting the font size to change when applying breakpoints as the screen ...

Ensuring the correctness of phone numbers by validating them with country codes through the use of

I'm currently working on validating phone numbers using intl-tel-input, following the example provided at Below is the code snippet I've been using: var telInput = $("#phone"), errorMsg = $("#error-msg"), validMsg = $("#valid-msg"); // initial ...

Issue NG0203 encountered during material import attempt

I've been encountering an issue with importing material. Despite using code similar to the examples on material.angular.io, I keep running into the ""inject() must be called from an injection context..." error. My goal is to create a simple table ...

The functionality of the Hubot script is restricted to Slack conversations where I initiate a direct message with the

At this very moment, my automated Hubot assistant is functioning properly. When I send the following message via direct message to the robot in Slack: qbot !npm bower The response provided by the robot contains a link: https://www.npmjs.com/package/bowe ...

The Express server is set up with CORS enabled, however, it continues to encounter issues when attempting to make asynchronous HTTP requests from

We're currently experiencing an unusual issue and are seeking assistance to resolve it. Initially, our Express server is functioning well as an API when accessed from the same domain. However, we also need to utilize this API on our computers for tes ...

Setting a default value within an input tag: A step-by-step guide

const [userData, setUserData] = useState([]); const handleUserInfo = (id) => { fetch(`https://602e7c2c4410730017c50b9d.mockapi.io/users/${id}`) .then(res => res.json()) .then(data => setUserData(data)) } <inpu ...

Checking to see if all the users mentioned in the message have been assigned a role

Hello everyone, I'm new to asking questions here so please bear with me. I am trying to retrieve all the users mentioned in a message and check if any of them have a specific role, such as the staff role. Thank you for your help! Edit: Here is the ...

Tips for getting involved in the Mojito repository on Github for javascript development

Looking for guidance on studying, understanding, and debugging code? I have a good grasp of javascript but unsure where to begin. I am familiar with Github and Mojito, but struggling to contribute to the platform. Any tips on how to get started with Moji ...

Show or conceal a child component within a React application

In my React render function, I am working with the following code: <div> <InnerBox> <div>Box 1</div> <HiddenBox /> </InnerBox> <InnerBox> <div>Box 2</div> & ...

Steps for accessing req.session in nextServerInit before rendering:1. Start by importing the

Currently, I am in the process of setting up a website using nuxt+express by running 'vue init nuxt-community/express-template' command. The specific feature I am focusing on is "auth". My goal is to maintain the user's information stored co ...

Tips on how to highlight a clicked list item:

I'm currently attempting to access the key={1} Element within my li. My goal is to set the activeItem in State in order to compare it with the clicked item later on. If they are equivalent, I want to apply an active class to that specific element. How ...

Build a unique array of identifiers extracted from an object

I am seeking advice on how to extract an array of IDs values by iterating through an object in React JS. const initialState = useMemo(()=> { return dataTable.filter(result => favorites.some(favorite => result.id === favorite.id)) },[ ...

Combining AngularJS with Servlets: A Seamless Integration

I am attempting to retrieve a JSON object from a servlet by calling a function through a link in my HTML code. Below is the HTML link that calls the fTest function: <td><a href="" ng-controller="minaplantaCtrl" ng-click="fTest(x.id_camion_descar ...

Cannot see the created item in Rails application when using RSpec, Capybara, Selenium, and JavaScript

Currently, I am in the process of developing a web store. The key functionality is already implemented where all products are displayed on one screen along with the list of ordered items. Whenever a product is selected for ordering, it should instantly app ...

Prevent form submission with jQuery during validation process

Currently, I am working on validating a form using jQuery. My main objective now is to have the submit button disabled until all fields are correctly filled in. To achieve this, I have implemented the following approach: http://jsfiddle.net/w57hq430/ < ...

Exploring Node.js with the power of EcmaScript through Javascript Mapping

I am currently using Map in NodeJS version 0.10.36 with the harmony flag enabled. While I am able to create a map, set and retrieve data successfully, I am facing issues with other methods such as size, keys(), entries(), and forEach as they are returning ...

Revamping elements according to ordered array. Angular version 4.3

Dealing with an array of data that needs to be sorted for displaying in a component seems to be a challenge. Despite having a functional code sample demonstrating the concept, the sorting is not reflected in the Angular app's DOM. The original data i ...

Leveraging Vue.js to preload data with client-side rendering

When it comes to server-side rendering in Vue, like with Nuxt, the process involves grabbing data using the serverPrefetch() function and rendering content on the server side. This allows for the request to return data to the user only after the initial do ...