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:

https://i.sstatic.net/4Saq3.png

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.

https://i.sstatic.net/hWut9.png

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

Leverage all the documents obtained from a collection to reference in a Vue component

I am attempting to display all documents from a Firestore collection in a table using refs, but I am unsure about accessing each field for template ref. getDocs(collection(db, "usr")) .then((querySnapshot) => { querySnapshot.forEach((doc ...

When utilizing Vuetify, I encountered an issue where attempting to print a page resulted in only the first page being displayed

My app utilizes the Vuetify framework. One particular page is dedicated to orders, and I'm looking to enable users to print it. The issue arises when there is a scroll on the page - only the first page gets displayed with a scrollbar: https://i.sta ...

Do not use a template for keying. Instead, place the key directly on physical elements

I'm trying to incorporate the image preview feature using the image component within the View Design framework, but I keep encountering an error. You can find the Component url here under Example 5. Below is the code snippet: <template> < ...

What could be causing the issue with this jQuery selector for the parent form element?

I created a form that connects a button with an attribute, but it's not hiding the parent("form"). However, when I try this, it works. $($("[editFormContent]").attr("editFormContent")).click(function(e) { e.preventDe ...

I'm interested in using JavaScript to create a URL for the current page with two additional parameters

Currently, I am utilizing the sharethis plugin within a smarty template. When sharing on Twitter, the link appears as follows: <span class='st_twitter_large' st_via="mediajobscom" st_url="MY URL HERE" displayText='Tweet'> My goa ...

Encountering an issue in Next.js when using getStaticProps: reading 'map' of undefined properties

The Image above shows the error and the code I have attempted.Server Error TypeError: Cannot read properties of undefined (reading 'map') This particular error occurred during the page generation process. Any console logs will appear in the term ...

Selective Circle Appending Techniques

I am having some issues with my bubble chart code. The data file I am working with contains instances where the GDPperCapita and/or LifeExpectancy values are either 0 or NaN, causing problems when appending circles to the chart. I would like to know if th ...

What is the best way to specify option values for selection in AngularJS?

...while still maintaining the model bindings? I currently have a select menu set up like this: <select class="form-control" ng-model="activeTask" ng-options="task.title for task in tasks"> </select> When an option is selected, it displays s ...

The complexity surrounding various versions of jQuery, the .noConflict method, and the jQuery migrate feature

I was tasked with making a large-scale website responsive, and decided to utilize Bootstrap as the framework. However, I encountered issues due to the jQuery version (v1.8.2) being used. In my development environment, I resolved this by including the follo ...

Trouble with Map method not displaying data in Next.js

I am currently working on a Map Method but facing an issue. The data 1,2,3,4,5 is successfully displayed in the console.log, but not showing on the website. import React from 'react' export default function secretStashScreen() { const numbers = ...

Interfacing Highcharts with Angular for seamless data binding across series

I am fairly new to using highcharts and I am having difficulty binding my data into the series parameter. In my controller, I have an array of objects that I want to display (when I use console.log, I can see that they are all properly there) this.plotDa ...

What is the best way to prevent the onClick event from triggering during the page rendering process?

I am currently working with React, Gatsby, and Material UI Buttons. I'm facing an issue where the most recently pressed button is getting disabled along with all other buttons when running my code. Despite already implementing bindings, as suggested b ...

Unable to add the div using a jQuery click event

Hey there, I'm looking to add a div dynamically when clicking on another div. Check out the code snippet below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title></title> <script src= ...

The specified package, [email protected], fails to meet the peerDependencies criteria set by its sibling modules

Encountering errors when attempting to run npm install. I'm puzzled why it's not working despite using the most recent version of React. npm ERR! peerinvalid The package <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail ...

React error: Updating state is only allowed on mounted or mounting components

I'm encountering this Error/Warning message in my console: The error message says: setState(...): Can only update a mounted or mounting component. Addressing the Component Mounting Process When it comes to mounting the component, here's the r ...

Arranging an Array of Objects in JavaScript by dual criteria

In my JavaScript code, I have an object structured like this: myArray[0] -> 0:"62", 1:8, 2:0, 3:"11" myArray[1] -> 0:"62", 1:8, 2:0, 3:"15" myArray[2] -> 0:"48", 1:8, 2:0, 3:"04" myArray[3] -> 0:"48", 1:8, 2:0, 3:"01" myArray[4] -> 0:"62", ...

Is there a variance in outcomes between constructing a pattern with a string and constructing a pattern with a regular expression "literal" in JavaScript?

Are there any distinctions between using RegExp literals versus strings? http://jsfiddle.net/yMMrk/ String.prototype.lastIndexOf = function(pattern) { pattern = pattern + "(?![\s\S]*" + pattern + ")"; var match = this.match(pattern); ...

Why is my Javascript XMLHttpRequest onreadystatechanged event not triggering?

I am facing an issue with my html file and a .txt file stored in the same directory on a webserver. In the html file, I have the following code: <html> <head> <script> window.onload = function() { receiveMessage(); } function recei ...

What could be the reason for a code running successfully in node but not in the REPL environment?

This is the current script I'm working with: const lib = require('./lib.js'); const fs = require('fs'); const graph = fs.readFileSync('../js-working-dir/add_graph.pb', 'utf8'); const sess = new lib.Session(gr ...

Minification of CSS - Vuetify

While working on my Nuxt project with Vuetify, I noticed that the page source is quite lengthy with 26k lines of code, most of which is generated by Vuetify's CSS. On comparing it with other pages, I see shorter code with difficult-to-read CSS. Is the ...