I had hoped to remove just one item, but now the entire database is being erased

I present it in this way

    <tr v-for="(foodItem, index) in filteredFoodItems">
       <td>{{ foodItem.name }}</td>
       <td>{{ foodItem.price | currency('£') }}</td>
       <td>{{ foodItem.category }}</td>
       <td><a @click="removeItem(index)" class="button is-danger is-outlined">
           <span>Delete</span>
           <span class="icon is-small">
              <i class="fas fa-times"></i>
           </span>
         </a>
      </td>
   </tr>

This is the method I use for deletion

router.delete('/', function (req, res) {
  let itemToRemove = req.body;
  let FoodItem = mongoose.model('FoodItem', FoodItemSchema);
  FoodItem
    .find(itemToRemove)
    .remove(itemToRemove, err => {
      if (err) return handleError(err);
    })
})

After clicking the button, instead of deleting the selected item from the database, it removed all data. I wanted to delete a specific item by using the index from the v-for loop and passing it as an argument to removeItem() on click. However, it deleted everything in the database. Any ideas on where I went wrong? Thanks in advance!

Below is the code for removeItem

removeItem(itemToRemove) {
            axios.delete('/api/menu', this.foodItems[itemToRemove])
                .then(response => {
                    console.log(response);
                })
                .catch(err => {
                    console.log(err)
                });
        }
    },

Answer №1

When looking at your router code, you are relying on the response body to determine what needs to be deleted. However, in your axios code, you are not actually accessing the response body; instead, you are only providing an array element. In order to address this issue...

Modify

axios.delete('/api/menu', this.foodItems[itemToRemove])

Change To

axios.delete('/api/menu', {data:this.foodItems[itemToRemove]})

By making this simple adjustment, it should resolve your problem.

Answer №2

Everything seems to be in order. However, it is important to incorporate the :key binding to ensure that the index is properly recognized during the list rendering process:

<tr v-for="(foodItem, index) in filteredFoodItems" :key="index">

In addition, when using a link tag, make sure to prevent its default behavior when applying a click handler:

@click.prevent="removeItem(index)"

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

Struggling with running a jQuery ajax request inside a function?

Below is my code for a jQuery Change Event: $("input[name=evnt_typ]").change(function(){ var request = $.ajax({ method: "POST", url: "ajaxRequest.php", dataType: "json ...

Tips for defining a function without an arrow as a parameter

Understand that there may be individuals quick to flag this as a duplicate question, but trust me when I say that I have exhaustively searched on Google for almost an hour before turning to ask here. methods: { stylizeHeader: debounce(event => { ...

Decide whether an angular rotation is within the camera's field of vision inside a spherical object

Seeking assistance with a three.js project. I have set up a camera inside a SphereGeometry at position (0,0,0) and am projecting an image on the sphere's wall. My goal is to create interactive JS elements outside of the threejs framework that respond ...

Issue with clientHeight not functioning properly with line breaks in Angular 2 application after ngAfterViewInit

I have successfully created a Gridify page in my Angular 2 application using the Gridify library. To initialize it, I've utilized a custom ngAfterViewChecked method: ngAfterViewChecked() { var selector = document.querySelector('.read-grid& ...

Implement safe instructions through communication between the client and server

I am currently using Fancy WebSockets in Javascript for communication with my php server to support my multiplayer game. At the moment, I am simply sending raw sockets (json) as Sending: {"command": "login", "data": {"id" : "1575","md5" : "6bd8937a8789a3 ...

What could be causing the input field state to remain static even as I type in the MUI textField?

In my React.js component, I am facing an issue where the textField is not updating when I try to type anything. Upon debugging, I discovered that when the first character is entered, the component re-renders and loses its previous state, causing the textF ...

Generating elements added at various depths within an HTML document with the help of JavaScript

create_new.append("div") .append("form").merge(update_5) .attr("action", d => d.market) .attr("target","_blank") .style("width","100%") .style("height","282") .append("input").merge(update_5) .attr("type","submit") ...

Ensuring continuous user login during webpage refreshes with the help of React and local storage

Currently, I am working on implementing the use of local storage to ensure that upon refresh, the user remains logged in rather than being signed out each time. Successfully, I have been able to store data in local storage by utilizing the following code ( ...

Utilizing ExpressJS to refresh database query after new record insertion

I'm a beginner in using expressJS and I have a question about querying the database (mongo in this case) to retrieve all records after adding one. exports.get = function (db) { return function (req, res) { var collection = db.get('n ...

Utilizing ES6 imports with module names instead of paths

Is there a way to import modules using just their name without the full path? For instance, can I simply use: import ViewportChecker from 'viewport-checker'; instead of import ViewportChecker from '../ViewportChecker'; I'd ...

Vue.js parent component sending new data: prop mutation detected

Encountering an issue in the console with the following error message: Instead, use a data or computed property based on the prop's value. Prop being mutated: "sortType" Within my root file, I have an API and filter function sending data to comp ...

Creating an interactive API endpoint in AngularJS for a DreamFactory stored procedure just got easier with these simple steps

If I am using a factory/service to access my API in DreamFactory. FoundationApp.factory('testAPI', function($resource, ChildID) { return $resource('http://Domain.com/rest/RemoteDB/_proc/TimeLog_Checkin(:ChildID)/?app_name=App&fields ...

How to assign a value in an HTML element using AngularJS

Currently, I am utilizing Angular JS to iterate through a portion of a scope that is initially a JSON array. My objective is to verify the existence of a specific value in that array. If the value exists, then certain actions should be taken. The code bel ...

Tips for troubleshooting objects within an Angular template in an HTML file

When I'm creating a template, I embed some Angular code within my HTML elements: <button id="btnMainMenu" class="button button-icon fa fa-chevron-left header-icon" ng-if="(!CoursesVm.showcheckboxes || (CoursesVm.tabSelected == 'curren ...

Looking for assistance with implementing a jQuery function for an onClick event on

I've been diving into learning jquery and managed to create a basic checkbox feature with a function that allows you to set all options as read-only by checking the "None of the above" button. <html> <body> <form id="diagnos ...

Connecting Node.js and Express with MySQL database

Today is my first time working with Node (Express) js, and I'm attempting to connect to a MySQL database. Here is the code snippet I found for my app.js file. app.js var express = require('express'), mysql = require('mysql'); // ...

the process of altering properties in vue js

After running my Vue file, I encountered the following console error. As someone new to Vue programming, I'm attempting to utilize a Syncfusion UI component to display a grid. Prop being mutated: "hierarchyPrintMode" I am unsure where to add the comp ...

Techniques for Extracting the Values of all ng-models within an ng-repeat Loop

How do I retrieve the total value of all ng-models within an ng-repeat loop using AngularJS? Below is my HTML code: <div ng-repeat="kind in plans.availableOptions"> <span class="payLabel text-left">{{kind.name}}</span> ...

Move router parameters to separate files to streamline and organize code

I have encountered a bit of an issue. I currently have the following code in my routing.js file where I define both my parameter and route. I have moved the routes to a separate router instance in my routing.js file, but I am struggling to separate the par ...

Angular 2 Error: Unresolved Promise rejection - Unable to assign value to reference or variable

I'm currently working on an Ionic 2 app that includes a barcode reader feature. However, I encountered the following issue while trying to display data: Unhandled Promise rejection: Cannot assign to a reference or variable! ; Zone: ; Task: Promi ...