Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

482
Views
Delete a user with Mongoose, Express

I am new to Express and MongoDB. I created a small web app in Node.js and am using Express.js and Mongoose. I can succesfully create a user and have a user sign in but I am having trouble with a user being able to delete their account.

I have a user.js file in my routes folder which is where I am writing the code to signup, signin, delete, etc. Here is a link to the project on GitHub ( https://github.com/NicholasGati/shopping-cart-2 ). The button to delete a user's account is in views/user/edit.hbs. I put the button in a form. When I click the button, the user is not deleted and I am redirected to '/' for some reason. Note: '/:id' in my routes/user.js file becomes '/user/:id'.

Here is the code in the routes/user.js file for the delete method:

router.delete('/:id', isLoggedIn, (req, res, next) => {
  User.findOneAndRemove({_id: req.params.id}, (err) => {
    if (err) {
      req.flash("error", err);
      return res.redirect("/user/edit");
    }

    req.flash("success", "Your account has been deleted.");
    req.logout();
    return res.redirect("/shop/coffee");
  });
});

Here is the form in views/user/edit.hbs:

<form action="/user/{{user.id}}" method="delete">
  <div class="form-group">
    <button type="submit" class="btn btn-danger">Delete Account</button>
  </div>
</form>

Also, here is the isLoggedIn function:

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect("/");
}
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Since you are new I think I should lead you to find the problem yourself:)

  1. Make sure about form methods.
  2. Make sure the route for user deletion is called.

If the markup doesn't seem right I am sorry cas I am using my phone to post this answer.

over 4 years ago · Santiago Trujillo Report

0

I had this exact same issue. I used an XMLHttpRequest from the client side in order to do this. I'm sorry I'm not experienced enough to explain why it worked this way and not from the node end, but it may have to do with form data being inherently designed to pass information, not delete information. In any case, try this solution.

In your client side code:

Your button code (form action shouldn't matter, and for that matter, the tag shouldn't either, since the logic is handled in the JS, but this is what I used):

<a href="/user/{{user.id}}"><button id = "del-btn" class="btn btn-danger">Delete</button></a>

         

Script to send HTTP request from the button click, this code should go in the same file as your button above, or as an include JS file that the HTML page has imported:

<script>
        var del_btn = document.getElementById("del-btn");
        del_btn.addEventListener("click", function(e) {

            var user = <%- JSON.stringify(user) %>;
            var xhr = new XMLHttpRequest();
            xhr.open("DELETE", "/user/" + user._id);
            xhr.onreadystatechange = function () {
                if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                    console.log(xhr.responseText);
                    window.location.href = "/users";
                }
            };
            xhr.send();


            //make XMLHttpRequest to delete the poll here
        }, false);
</script>

in your server side route, note how the response is just a success code. It's the XMLHTTP Request from the client side that does the redirection:

  app.delete('/user/:id', isLoggedIn, function(req,res){
          User.remove({
            _id: req.params.id,
            ownerID: req.user._id
          }, function (err, user) {
            if (err)
              return console.error(err);

            console.log('User successfully removed from polls collection!');
            res.status(200).send();


          });

  });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!