How to delete rows of data using sequelize?
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
Related videos on Youtube
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, 2022Comments
-
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
can someone help? for reference this is my repo https://github.com/SpaceXar20/sql_library_manager-updated
-
Erik L about 5 yearsI updated my post, I modified my code but I still have some issues
-
Erik L about 5 yearsI have modified my post