Delete a document via Mongoose and Express by clicking a button

I try to delete a connected account via Express and mongoose. When the user clicks on the button (confirmation on his willing to delete his account), I want his account remove from my user’s collection.

My HTML:

<div class="button__remove">
     <button class="modal__submit modal__remove--ann" id="btn-remove">Annuler</button>
     <button class="modal__submit modal__remove--conf" onclick="location.href='/fr/supprimercompte'">Supprimer</button>
</div>

My Express code:

router.get('/supprimercompte', (req, res) => {
  User.findByIdAndDelete(req.params.id, (err) => {
    if(err){
        res.redirect("/fr/compte");
    } else {
        res.redirect("/fr");
    }
 });
})

Nothing happens when I click on the button. But my User is already connected.
Have I to use a delete method ?

27 thoughts on “Delete a document via Mongoose and Express by clicking a button”

  1. you should path the id to the route like with /:id and send the id from the client side to the route

    router.get('/supprimercompte/:id', (req, res) => {
            User.findByIdAndDelete(req.params.id, (err) => {
              if(err){
                  res.redirect("/fr/compte");
              } else {
                  res.redirect("/fr");
              }
           });
        })
    

    for client side

    `/fr/supprimercompte/${id}`
    
    Reply

Leave a Comment