Increase the value in Firestore using FieldValue in a Vue application

Currently, I am working on updating a value in a Firestore database document by 1. After some research, I came across the FieldValue.increment(1) method. My objective is to create a form with two fields (Host/Scout) where I can input the name of a person whose host or scout value needs to be incremented. This is the structure of my Vue component:

<template>
  <div class="add-wave">
    <h3>Add Wave</h3>
    <div class="row">
      <form @click.prevent="addwave()" class="col s12">
        <div class="row">
          <div class="input-field col s12">
            <input type="text" v-model="host" />
            <label class="active">Host</label>
          </div>
        </div>
        <div class="row">
          <div class="input-field col s12">
            <input type="text" v-model="scout" />
            <label class="active">Scout</label>
          </div>
        </div>
        <button type="submit" class="btn">Submit</button>
        <router-link to="/member" class="btn grey">Cancel</router-link>
      </form>
    </div>
  </div>
</template>

<script>
import db from "../data/firebaseInit";
export default {
  data() {
    return {
      host: null,
      scout: null
    };
  },
  methods: {
    addwave() {
      db.collection("members")
        .where("name", "==", this.$route.params.host)
        .get()
        .then(querySnapshot => {
          querySnapshot.forEach(doc => {
            doc.ref
              .update({
                host: db.FieldValue.increment(1)
              })
              .then(() => {
                this.$router.push({
                  name: "member",
                  params: { name: this.name }
                });
              });
          });
        });
    }
  }
};
</script>

Although everything seems to compile fine, I encounter an error when I try to enter a name in each input field - "FirebaseError: 'Function Query.where() requires a valid third argument, but it was undefined'."

I'm unsure why this error is occurring and how I can resolve it. Any guidance in the right direction would be greatly appreciated.

Answer №1

Here are a couple of issues with the current code:

  • Instead of this.$route.params.host, you should use this.host, which is where Vue binds the host parameter.

  • If db is created from firebase.firestore(), referencing the static FieldValue for the increment function as firebase.firestore.FieldValue is necessary. Make sure to import this symbol into your code correctly since firebase is only accessible in the firebaseInit module.

To import, add this line at the top of your <script> section:

import firebase from "firebase/app";

Keep in mind that using counters may hit scalability limits due to the per-document update rate limit of 1 update per second. You can refer to Firebase documentation for a solution on how to build distributed counters across multiple documents once you exceed this limit. This also showcases proper usage of the increment method.

Answer №2

When dealing with the issue of FieldValue.increment(1), it is necessary to include FieldValue in your initialization file named firebaseInit. Here's how you can do it:

import firebase from "firebase/app"; 
import "firebase/firestore"; 
import firebaseConfig from "./firebaseConfig"; 

const firebaseApp = firebase.initializeApp(firebaseConfig);

const db = firebase.firestore();
const fv = firebase.firestore.FieldValue;

export { db, fv };

Next, within your component, you will need to write:

import {db, fv} from "../data/firebaseInit";

//....
fv.increment(1)

Regarding the second possible issue, when referring to the vue router documentation, you will find:

$route.params

An object that includes key/value pairs of dynamic segments and star segments. If there are no params provided, the value will be an empty object.

If you are not passing any specific key/value pairs in the URL, you will have to utilize another Route object property, namely $route.path

$route.path

A string representing the current route path, always resolved as an absolute path. e.g. "/foo/bar".

To implement this, proceed as follows:

  db.collection("members")
    .where("name", "==", this.$route.path.substr(1))
    .get()
    ...

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

Ways to maneuver past clustering

I'm currently facing a challenge with my express server where I am attempting to set up a scheduled job for sending automated emails at a specific time (10:00 am). To achieve this, I am utilizing the node-cron package for scheduling purposes. However ...

Styling your Vuetify V-data-table with CSS

Struggling to add extra spacing between table rows, despite inspecting the page and verifying that my styles are not being overridden. Have read other Vuetify posts on applying CSS but still no luck. Any suggestions for why I can't style my table as d ...

Error in VueJS occurring following the import of a function into a JavaScript file

I've created a JavaScript script for sending data to a database, and I want to import it into my .vue file so that I can use it on button click. However, when I import the script, Vue displays the following error message and nothing appears on the pag ...

My form does not receive the Bootstrap classes when using the jQuery script

**Why isn't my jQuery script coloring the rows as expected when certain conditions are met (I italicized the specific part of the code)?** Here is the HTML CODE for the POLL: <form id="pollForm" class="mb-4"> <d ...

How can I dynamically generate HTML based on the path of an SVG that is clicked, and what is the best approach to display or hide this generated HTML on the web page?

Question I'm facing an issue with my SVG implementation where Users can click on various body parts, causing the clicked body part to gain the 'active' class. This class styles my CSS and sets variables in my JS. The challenge I'm enco ...

Is it possible to access an external website by clicking on a link within a DIV element?

I have a basic website set up like this sample.php <html> <head></head> <body> <a id="myLink" href="http://sample.com">Click!</a> </body> </html> I displayed this website within a DIV-Container on a ...

Leveraging Github CI for TypeScript and Jest Testing

My attempts to replicate my local setup into Github CI are not successful. Even simple commands like ls are not working as expected. However, the installation of TypeScript and Jest appears to be successful locally. During the Github CI run, I see a list ...

Include a future date with a date extracted from a JSON response

I have retrieved a date from a JSON response. After confirming that the date is indeed a valid date type, I am having trouble setting it to a future date. The snippet of code below shows my attempt: $rootScope.until = response.data.data.dateReceived; //r ...

Is there a way to display shortened text only when hovering without altering the height of the list box?

Here is my script for a vue component : <template> ... <b-card-group deck v-for="row in formattedClubs"> <b-card v-for="club in row" img-src="http://placehold.it/130?text=No-image" img-alt="Img ...

What is the best way to modify the text color within a Navbar, especially when the Navbar is displayed within a separate component?

First question on StackOverflow. I have a Next App and the Navbar is being imported in the _app.js file. import Navbar from "../Components/Navbar"; function MyApp({ Component, pageProps }) { return ( <> <Navbar /> ...

The NextJS 13 return block loads and displays before the useEffect function is executed

I am currently in the process of developing a Next.js 13 application that incorporates next-auth for session management and interacts with Firebase Firestore to verify the existence of a user in the database. If the user is found, they should be directed t ...

Observable method utilizing a recursive approach for delayed execution

Trying to implement a recursive server connection method with a delay in Angular 8. This is what I attempted: public connectToServerSafely(): Observable<boolean> { if (this.isConnecting) { return this.connectToServerSafely().pipe(delay(5000)) ...

Sending a POST Request between two websites using JavaScript

I am facing an issue where I need to send a POST request from an application on SERVER1 to another application running on SERVER2. SERVER1: <form name="submitForm" method="POST" action="http://SERVER2:4120/download_item/&qu ...

The continuous progression of code execution

Having a background in Java, I decided to dive into learning Angular2 recently and have been working on it. However, I encountered a confusing situation in one of my projects that I could not figure out. For the pagination feature I was implementing, I ne ...

How can I utilize a Vuex store to establish a default image?

I'm trying to set a default image for the user in vuex by configuring my vuex store like this state:{ default_image: "../assets/images/users/1.jpg" }, getters:{ Image:state=>state.default_image, } Next, I have the App.vue file <templ ...

What is the best way to combine limit and fill() in one array?

I am looking to incorporate both limit and fill within the same array. var array = new Array(4).fill({}); var limit = 4; If there are dynamic records, the number may vary but I only need 4 records to display. For example: eg-1 records = 20 It should disp ...

Tips for tackling drag and drop functionality with only HTML, CSS, and JavaScript

Currently, I am faced with a challenge involving drag and drop TEST. Observing the image provided below, you will notice 3 columns each containing 3 small boxes of varying colors. These boxes are draggable, meaning they can be moved between columns follow ...

Mongoose doesn't support saving extensive text-data

I am facing a challenge while trying to save an extensive text into my mongodb database as it keeps crashing. I am in the process of creating a snippet manager and below you can find the error code I encountered: { [MongoError: Btree::insert: key too larg ...

The issue of THREE.js failing to render .obj files with .mtl files has been a common problem when exporting assets

After further investigation, it seems that the issue lies with the exported files and their formatting, although I am unsure of the exact problem. Interestingly, additional example models I downloaded render perfectly fine. I have encountered a problem wi ...

Extract the URL contained within the <a> tag using the src attribute of an <img> tag automatically

At first glance, this question may seem odd, but I haven't discovered any other method to resolve the issue. Please bear with me as I explain my objective in detail! Currently, I am utilizing a lightbox to showcase an image that enlarges when clicked ...