Heads up! To view this whole video, sign in with your Courses Plus account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
In this video we'll update rows of data in a table.
Important Notice About the findById()
Method
Since the recording of this workshop, the Sequelize findById()
method has been deprecated and replaced by the findByPk()
method.
Using the findByPk()
method, the code for the routes to get the edit article form and update an article look like this:
/* Edit article form. */
router.get('/:id/edit', function (req, res, next) {
Article.findByPk(req.params.id).then((article) => {
res.render('articles/edit', { article: article, title: 'Edit Article' });
});
});
/* PUT update article. */
router.put('/:id', function (req, res, next) {
Article.findByPk(req.params.id).then((article) => {
return article.update(req.body);
}).then((article) => {
res.redirect('/articles/' + article.id);
});
});
Sequelize Methods
We're halfway done with
our crude operations.
0:00
We've created and read rows of data.
0:02
Now let's update our articles.js routes
file to add routes for editing articles.
0:05
There's an edit form route and
0:19
There's the edit form routes and the HTTP
put routes to update a given article.
0:26
Both of these routes require
the article to be found first.
0:34
Let's use the findById method
first in the edit form.
0:42
Once the article is found,
it is passed into our form here and
0:59
in our puts update URL handler,
1:05
let's first find the article and
then update the article.
1:08
Once the update has happened, then we can
redirect to the individual article page.
1:47
What's happening here is that the update
method is returning a promise.
2:05
Returning a promise passes the next
value down the then chain.
2:10
In other words,
the article here is the updated article.
2:16
Let's restart the web server
2:22
And edit our second article's text.
2:32
And update it.
2:40
And it works.
2:42
In the next video,
we'll take a look at deleting entries.
2:44
You need to sign up for Treehouse in order to download course files.
Sign up