Update is not performed in the Database using Sequelize and Nodejs

Asked

Viewed 97 times

2

I have the following route that is responsible for receiving the data coming from a form and doing an update of the data that is in my database

router.post('/articles/update', (req, res) => {
    let id = req.body.id; 
    let title = req.body.title;
    let body = req.body.body;
    let category = req.body.category;

    Article.update({title: title, body: body, categoryId: category, slug: slugify(title)}, {
        where: {
            id: id,
        }
    }).then(() => {
        res.redirect('/admin/articles');
    }).catch((error) => {
        console.log('Error' + error)
    });
})

When the route is executed, all actions are carried out including I am redirected to the admin/Articles page (falls in Then once the function has returned success) but the data is not changed in the database. Why?

  • 1

    In the code posted there is no error at all, so much so that is executed the then(), probably the error is elsewhere. Unless the values are not in agreement. You have already given a log these values of the variables there to see, mainly the variable id?

  • 1

    Because it’s expensive!! I went there and in fact that’s where the problem is, the id (req.body.id) is returning empty. Now is to find out the reason, since the name of the form where I send the ID is exactly the one I get on my route. But this has saved enough, thanks man! D

1 answer

1

router.post('/articles/update', (req, res) => {
  const { id, title, body, category } = req.body || {}

  try {
    Article.update({ title, body, categoryId: category, slug: slugify(title) }, { where: { id } })
    res.redirect('/admin/articles')
  } catch (error) {
    console.log('Error:' + error)
  }
})

Maybe if you play inside a try/catch may help you debug better

Browser other questions tagged

You are not signed in. Login or sign up in order to post.