'How to delete rows of data using sequelize?

So I have the following router in a pug file called books.js, in this router I am using the Sequelize ORM to find a row of data based on the id in order to deleted

    /* - Deletes a book. Careful, this can’t be undone. 
It can be helpful to create a new “test” book to test deleting.

create the post /books/:id/delete route*/
router.post('/:id/delete', function(req, res, next){
  Book.findOne({where: {id: req.params.id}}).then(function(book){
    return book.destroy();
  }).then(function(){
    res.redirect('/books/');  
  })
});

this is the form inside a pug file called update-book.pug where I have a button that once pressed it should delete the row of data and redirect to /books

form(action="/books/" + book.id , method="post" onsubmit="return confirm('Do you really want to delete this book?');")

Once I press the delete button, I get the 200(ok) status code, but my browser stays in the same page

enter image description here

can someone help? for reference this is my repo https://github.com/SpaceXar20/sql_library_manager-updated



Solution 1:[1]

router.delete('/:id/delete', async (req, res, next) => {
  let book = await Book.findOne({where: {id: req.params.id}}).catch(e => {
     console.log(e.message)
  })
  if (!book){
    console.log("err");
  }
  book.destroy();
  res.redirect('/books');
});

Solution 2:[2]

because you are using return statement your code should be:

try{
  await Book.destroy({where:{id:req.params.id})
   res.redirect('/')

 }
 catch(e){
  console.log(e)
   // handle error better
 }

also you do not need to find and then delete this query finds and delete automatically

Solution 3:[3]

you can also delete using query

 const result=sequelize.query("DELETE FROM books WHERE id="+req.params.id).then((res) =>{
    return Array.from(new Set(res));
 })

Solution 4:[4]

You have defined a form with method as 'POST' and your router expects a 'DELETE' method. So either change your router to accept 'POST' method or make an AJAX request with method 'DELETE'.

Solution 5:[5]

Why use two separate queries when where condition can be put inside the destroy function of sequelize? And in response, u get the number of records deleted and can put check there if anything deleted or not.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zulhant Arif
Solution 2 TGod
Solution 3 Bhadresh
Solution 4 himank
Solution 5 Rohit Dalal