Erik L
Erik L

Reputation: 195

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

Upvotes: 2

Views: 16141

Answers (5)

Bhadresh
Bhadresh

Reputation: 429

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));
 })

Upvotes: 1

TGod-Ajayi
TGod-Ajayi

Reputation: 61

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

Upvotes: 2

Rohit Dalal
Rohit Dalal

Reputation: 866

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.

Upvotes: -1

Zulhant Arif
Zulhant Arif

Reputation: 31

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');
});

Upvotes: 2

himank
himank

Reputation: 439

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'.

Upvotes: 0

Related Questions