【问题标题】:How to delete rows of data using sequelize?如何使用 sequelize 删除数据行?
【发布时间】:2022-01-29 10:37:31
【问题描述】:

所以我在一个名为 books.js 的 pug 文件中有以下路由器,在这个路由器中我使用 Sequelize ORM 根据 id 查找一行数据以便删除 p>

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

这是一个名为 update-book.pug 的 pug 文件中的表单,其中我有一个按钮,一旦按下它就会删除该行数据并重定向到 /books

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

按下删除按钮后,我得到 200(ok) 状态码,但我的浏览器停留在同一页面中

有人可以帮忙吗?供参考,这是我的回购https://github.com/SpaceXar20/sql_library_manager-updated

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案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');
    });

    【讨论】:

    • 我已经修改了我的帖子
    【解决方案2】:

    因为您使用的是 return 语句,所以您的代码应该是:

    try{
      await Book.destroy({where:{id:req.params.id})
       res.redirect('/')
    
     }
     catch(e){
      console.log(e)
       // handle error better
     }
    

    您也不需要查找然后删除此查询会自动查找并删除

    【讨论】:

      【解决方案3】:

      您也可以使用查询删除

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

      【讨论】:

        【解决方案4】:

        您已经定义了一个带有“POST”方法的表单,并且您的路由器需要一个“DELETE”方法。因此,要么将您的路由器更改为接受“POST”方法,要么使用“DELETE”方法发出 AJAX 请求。

        【讨论】:

        • 我更新了帖子,修改了代码,但仍有一些问题
        【解决方案5】:

        当 where 条件可以放在 sequelize 的 destroy 函数中时,为什么要使用两个单独的查询?作为回应,你会得到删除的记录数,并可以在那里检查是否删除了任何内容。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-02-08
          • 2023-02-01
          • 2016-02-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-19
          • 1970-01-01
          相关资源
          最近更新 更多