How to delete rows of data using sequelize?

10,345

Solution 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

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 3

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

Share:
10,345

Related videos on Youtube

Erik L
Author by

Erik L

I am currently learning html, css and Javascript in order to become a front-end developer. I have a GitHub account linked to my profile where I will continually publish my projects in there.

Updated on June 04, 2022

Comments

  • Erik L
    Erik L almost 2 years

    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

  • Erik L
    Erik L about 5 years
    I updated my post, I modified my code but I still have some issues
  • Erik L
    Erik L about 5 years
    I have modified my post