Sequelize’s Update Method — example included

Sequelize is a wonderful API, but trying to figure out what is going on can be a bit of a challenge. The documentation is confusing and there are not many outside resources. Today I am going to talk about the update method in Sequelize with examples within an express PUT route.

Let’s say we have the following Book model in Sequelize:

var Book = db.define(‘books’, {
title: {
type: Sequelize.STRING
},
pages: {
type: Sequelize.INTEGER
}
})

Ideally, we would want to be able to update the title of a book. I have written the following express PUT route:

router.put(‘/book/:bookId’, function (req, res, next) {
Book.update(
{title: req.body.title},
{where: req.params.bookId}
)
.then(function(rowsUpdated) {
res.json(rowsUpdated)
})
.catch(next)
})

This is great because it updates the database with the new book title for the matching book id. But it returns the number of rows updated. This is rarely useful on the front-end. More likely we would want to do something with the updated book on the front-end. Of course, we can then query the database in a .then and get that books information, but there has to be a better way! And there is.

If we include in the second parameter of the update returning: true then update method will return the number of rows updated as well as the updated book.

The following code will update a book in a PUT request and send back the updated book to the front-end:

router.put(‘/book/:bookId’, function (req, res, next) {
Book.update(
{title: req.body.title},
{returning: true, where: {id: req.params.bookId} }
)
.then(function([ rowsUpdate, [updatedBook] ]) {
res.json(updatedBook)
})
.catch(next)
})

As you can see, accessing the updated book is still a little tricky. I have destructured what update is returning so I can easily access the updated book because it is within an array that’s within an array.

Now we can update an entry in the database and easily access the updated book afterwards. If you have any questions or want to commiserate over the Sequelize documentation, email me (sarahherr02@gmail.com)!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.