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 retrieve single and multiple rows of data from tables.
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 route to get an individual article looks like this:
/* GET individual article. */
router.get('/:id', function(req, res, next) {
Article.findByPk(req.params.id).then((article) => {
res.render('articles/show', { article: article, title: article.title });
});
});
Sequelize Methods
Now let's start reading from the database.
0:00
First we'll find individual posts.
0:03
Down here we have the get route
found individual article.
0:16
I've created a simple synchronous
function called find that gets the ID
0:20
from the route, and
searches from the static articles.
0:25
We can use SQLizer's find by ID
method to find an article by the ID.
0:29
Now we can get rid of the static articles
at the top here and define function too.
1:03
Next, let's work on getting
all the articles back.
1:16
In the get route for all of the articles
we can use SQLizer's find all method.
1:20
This will retrieve all of the articles,
instead of a single article.
1:57
Let's restart the server.
2:05
This should now retrieve and
show all of the blog posts.
2:08
Let's create another blog post.
2:14
My second Blog Post.
2:20
Authored by me.
2:28
And we can have any old
text in this body here.
2:31
It shows correctly.
2:41
And when we go back to the article
list page, we have a problem.
2:43
The latest article appears last.
2:47
We need to order the results.
2:51
The findAll method can
take an options object.
2:58
Within that you can add any number of
criteria to filter the results including
3:04
order by to order a result
set you use the order key
3:09
with an array of a race.
3:17
Each array includes the column
you'd want to order by.
3:21
And in which order,
ascending or descending.
3:32
It's an array of a race because
you can order by multiple columns.
3:39
In this case, it's only one,
and it's in descending order.
3:44
Let's reboot the server now,
and go back to the list page.
3:52
And now the articles
are in the desired order.
4:00
Next, let's work on updating models.
4:04
You need to sign up for Treehouse in order to download course files.
Sign up