Search code examples
node.jsexpresspug

Handling delete operation in express + pug template engine


I'm learning express and have created a to-do list app in express with pug template engine. In this app, I can add and view to-dos. Now I want to add a delete functionality.

My pug code to render the to-do list is:

  ol
  each val in toDoList
    li= val.taskName
    a(class='button' href='/todos/'+val._id) delete

Here's my express code to handle the delete:

app.delete('/todos/:id', function(req, res){
    db.collection('todos').findOneAndDelete({id: req.params.id}, function(err, results) {
      if (err) return res.send(500, err);
      res.redirect('/');
  });

});

I am getting this error Cannot GET /todos/5e570f67ed9efba99c938719.

What am I doing wrong and how can I fix it?

Thanks!


Solution

  • Why you are getting the error:
    The link element: a(class='button' href='/todos/'+val._id) delete is going to render a link element like this: <a class='button' href='/todos/5e570f67ed9efba99c938719'>delete</a>(assuming val._id is 5e570f67ed9efba99c938719).

    Clicking this link won't delete the todo but instead, take you to a page whose URL is something like this /todos/5e570f67ed9efba99c938719 and this would cause the client app make a GET request to your server for that route. Since you do not have any route-handler matching the requested route from the client app in the server, you get the error: Cannot GET /todos/5e570f67ed9efba99c938719.

    The Fix
    To delete the todo, what you need to do is add an event listener to the link such that when you click it, instead of just redirecting you to some page, the handler attached to the event listener would be executed to reach out to your server and delete the todo. A sample implementation:

    // Add some more properties to the delete button
    a(class='button delete-todo' data-articleid=val._id href='/todos/'+val._id) delete
    

    And in a <script /> tag or a javascript file that would be loaded with the pug template, add this:

    // SOURCE: https://github.com/elvc/node_express_pug_mongo/blob/master/public/js/main.js
    $(document).ready(function(){
      $('.button.delete-todo').on('click', function(e){
        e.preventDefault();
        $target = $(e.target);
        const id = $target.attr('data-articleid');
    
        $.ajax({
          type: 'DELETE',
          url: '/todos/'+id,
          success: function (response){
            // Whatever you want to do after successful delete
            console.log(response);
            alert('Deleting article');
          },
          error: function(err){
            // Whatever you want to do after a failed delete
            console.error(err);
          }
        });
      });
    });