Mean Stack involves the interaction between the client controller and the server controller using routes to communicate and call server methods

I am currently developing a mean stack application and encountering difficulties when attempting to send requests to the Express/Node server in order to delete an element from an array in Mongo. Below is my schema for reference:

var DeckSchema = new Schema({
  name: {
    type: String,
    default: '',
    required: 'Please fill Deck name',
    trim: true
  },
  card: [{
    name: { 
      type: String, default: '', 
      trim: true,
      required: 'Please fill Card name'
    },...

Provided below is the client-side route I have set up:

.state('decks.card', {
        url: '/:deckId/card/:cardId',
        templateUrl: 'modules/decks/client/views/view-card.client.view.html',
        controller: 'DecksController',
        controllerAs: 'vm',
        resolve: {
          deckResolve: getDeck,
          cardResolve: getCard
        },...



function getDeck($stateParams, DecksService) {
    return DecksService.get({
      deckId: $stateParams.deckId
    }).$promise;
  }
  function getCard($stateParams, RemoveCardService) {
    return RemoveCardService.get({
      deckId: $stateParams.deckId,
      cardId: $stateParams.cardId
    }).$promise;

Below are the details of the server-side routes:

app.route('/api/decks/:deckId/card/:cardId').all()
    .get(decks.read)
    .put(decks.update)
    .delete(decks.deleteCard);

  // Finish by binding the Deck middleware
  app.param('deckId', decks.deckByID);
  //app.param('cardId', decks.cardByID); This causes errors

Also, here is the server-side controller code snippet:

 exports.deleteCard = function(req, res) {

    res.send('In deleteCard');
    Deck.update(
        {'_id': req.body.deck_.id}, 
        { $pull: { "card" : { id: req.body.deck.card._id } } },
    false,
    true 
    );
      //decks.update( {id: req.params.deckId}, { $pullAll: {id: [req.params.cardId] } } )
    };

Additionally, included is the middleware logic:

exports.cardByID = function(req, res, next, id){

    if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Card is invalid'
    });
  }
      Deck.findById(id).populate('card','user', 'displayName').exec(function (err, deck) {
    if (err) {
      return next(err);
    } else if (!deck) {
      return res.status(404).send({
        message: 'No Card with that identifier has been found'
      });
    }
    req.deck.card = deck.card;
    next();
  });
};

I am struggling to execute the deleteCard method in the client controller. The expected "In DeleteCard" message is not being displayed in the console, and I am unable to identify the issue. If further information is required, please let me know. Thank you in advance!

Answer №1

To delete a record, you will need to send a "DELETE" request from your client side. If you are using Angular, it is recommended to utilize the $http service for this purpose.

$http({
    method: "DELETE",
    url: '/api/decks/111/card/222'
})

Within your DecksController, you should include functionality similar to the following:

angular.module('myapp')
    .controller('DecksController', ['$scope', '$http',  function ($scope, $http) {
        $scope.deleteCard = function (deckId, cardId) {
            $http({
                method: "DELETE",
                url: '/api/decks/'+deckId+'/card/'+cardId
            })
            .then(function (resp) {
                console.log('response from server', resp)
            })
        }
    }]);

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

Anticipate feedback from Python script in Node.js

I have developed a website using nodejs and express, but I am facing an issue with integrating a python script for face recognition. The problem lies in the fact that when I invoke this script from nodejs using child-process, it takes around 10 to 20 secon ...

JavaScript-powered server polling

What are some effective strategies for continuously refreshing data from a server using JavaScript in an application with high refresh rate requirements? The front-end is developed using jQuery, while the backend utilizes Java Spring Framework. One exampl ...

Is it possible to swap the src of the Next.Js Image Component dynamically and incorporate animations in the

Is there a way to change the src of an image in Nextjs by using state and add animations like fadein and fadeout? I currently have it set up to change the image source when hovering over it. const [logoSrc, setLogoSrc] = useState("/logo.png"); <Image ...

Does Express cache static files when serving them?

The documentation for ExpressJS does not provide details on how static files are loaded. My inquiry is regarding the loading process of static files: Are they fetched from the disk every time a request is made? Or is there some form of caching mechanism i ...

Transform every key and value into an array

How can I separate each key and value into individual arrays? Here is the current data: var inputArray = { "3/10/2017": 52, "3/11/2017": 58, "3/12/2017": 70, "3/13/2017": 76 } The desired output should be: var outputArray = [ ["3/10/2017", 52 ...

Troubles arise when hovering over and connecting endpoints in jsPlumb

I'm currently facing two challenges with my project. Follow this link for more details. 1) The hover effect is working perfectly on the endpoints, but I can't seem to change the colors of my connector when hovering over it. Any suggestions? (Ref ...

When you click anywhere on the page, JavaScript's method __dopostback is triggered

I'm encountering an issue in my asp.net application where I have an html table. Specifically, when a user clicks on a td element within the table, I use JavaScript to store the id of that td element in a hidden field. Afterwards, I trigger __dopostbac ...

Ideal synergy between individuals using mongoose

Seeking to create ideal pairings among users using mongoose. Check out this sample schema: username: "Nicolas", fruitiwant:["apple", "orange"], fruitihave: ["banana"] I aim to generate a JSON output showcasing users who have perfect matches. User A desir ...

Display icon within ng-bind-html when the value is not true

Is there a way to integrate a fontawesome icon into ng-bind-html on ui-select based on a boolean value? <span ng-bind-html="project.IsActive == false && <i class="fa fa-ban" aria-hidden="true"></i> | highlight: $select.search">& ...

Execute JavaScript using "matches" without the need for the page to refresh

I have been developing a school project which involves creating a Chrome extension to streamline the Checkout process on a website. In my manifest.json file, I specified that a content.js file should run when it matches a specific URL. "content_script ...

How can user data be logged in ASP.Net Core when a check box is selected?

Struggling to discover a way to secretly log user information such as their username when a checkbox is selected. The goal is to capture this data without the user's knowledge. Here is the code: This checkbox is a custom switch from MDB <div> ...

Is the concept of Controlled and Uncontrolled Components in VueJs similar to that of React?

When it comes to React, there is a distinction between controlled and uncontrolled components explained in detail at this link. Controlled components function within the React model where state is managed in the virtual DOM. In contrast, uncontrolled com ...

The express nodejs web server is moving at a snail's pace, taking anywhere from 4 to 6 seconds to load each

I have been working on a personal cloud server using express and nodejs to serve static files. During development, I added some script files which caused the webserver to suddenly load very slowly upon reloads. Upon inspecting with chrome dev tools, I disc ...

The tooltip feature is malfunctioning

The content: <table class="table table-hover"> <?php foreach ($query as $row){ echo '<tr ><td > <label class="checkbox"> '.form_checkbox('delete[]', $row['link']).anchor("site ...

Something went wrong with @wdio/runner: unable to establish session

After successfully developing cucumber tests that passed and tested some URLs with Chrome, I encountered errors when uploading to the pipeline despite the tests succeeding. Webdriver generated the following errors: INFO webdriver: DATA { 57[0-0] capabili ...

Incorporating NodeJS, React, and the Next Framework to expand the route's path

Currently, I am in the process of setting up a NodeJS application using the Next framework for both client and server-side rendering. My goal is to add a specific path to the routes/URLs generated by the application. The server-side rendering appears to be ...

I'm unsure of the date format, could you guide me on how to convert it?

Dealing with formatting timestamps can be tricky, especially when you have different formats to work with. For instance, my AngularJS plugin returns timestamps in this format when printed in the JavaScript console: Sun Mar 30 2014 14:00:56 GMT-0400 (Easte ...

Merge the content of a single file with the contents of several other files using Gulp

I'm still getting the hang of Gulp, so I hope this question isn't too basic. My project is pretty complex with multiple files, and thanks to Gulp's magic, I can combine, minify, babel, and more. I've been using Grunt for a long time, so ...

A technique for simultaneously replacing two values in a single call to the replace function

Is there a way to replace two or more instances at once with a single replace call? I have not attempted anything yet, as I am unsure of how to proceed. let links = { _init: "https://%s.website.com/get/%s", } Here, you can see that I have a link wi ...

Removing filters dynamically from ng-repeat in Angular

I am currently using ng-repeat to display a list of staff members: <div ng-repeat="user in staff | profAndDr"> There is also a custom filter called 'profAndDr' that only shows people with the titles "Dr." and "Prof.": app.filter('pr ...