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
Top comments (1)