DEV Community

coscoaj1
coscoaj1

Posted on

How to complete a PUT request in Sequelize

mysql #database

How to complete a PUT request in Sequelize ORM:

If the first database you learned on was MongoDB, coming to MySQL you may expect the .update method in Sequelize to return the updated row, like how in mongoose .findByIdAndUpdate returns the found document. Instead, you will get back just an array with a single number in it. For example: [1]. What is going on here? According to the Sequelize docs:

“The promise returns an array with one or two elements. The first element is always the number of affected rows, while the second element is the actual affected rows (only supported in postgres with options.returning true).”

So to get back the actual row data, say if you need to send it back to your frontend to keep the UI updated, you will have to call the Sequelize .findByPk method after .update. The second part of your PUT route will look something like this

  const returnUpdatedPerson = await Person.findByPk(req.params.id); // finds the updated row
  if (!returnUpdatedPerson) throw "Error while Fetching Data"; //catches errors.
  res.status(200).json(returnUpdatedPerson); //returns it
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
meirlamdan profile image
meirlamdan • Edited on
// Way 1
const user= await User.findOne({ where: { firstName: 'John' } });
await user.update({ lastName: "Jackson" }
//or
await User.update({ lastName: "Jackson" }, {
  where: {
    lastName: null
  }
});
// Way 2
const user= await User.findOne({ where: { firstName: 'John' } });
user.lastName = "Jackson" 
await user.save()
Enter fullscreen mode Exit fullscreen mode