Sequelize: Querying Basics using findAll

Mike Frey
InstructorMike Frey
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 5 years ago

Sequelize has a powerful query mechanism, this lesson teaches the basics of querying using the findAll function.

[00:00] I have a file named "Post JS" which sets up Sequelize, and defines and exports my post model. The post's table is pre-loaded with records ready to be queried. In Find JS, I have a reference to the post model, which I'll use to query the post's table, and a little helper function to log instance data to standard out.

[00:26] Sequelize provides a number of class functions on models that are useful for querying data. Using the "Find All" method, I can ask Sequelize to fetch a list of all posts that have the visible attributes set to true. Find All returns a promise that will resolve with an array of post instances that all just loop through to log to standard out.

[00:52] When Find JS is run in node, I see the select query runs as well as all the attributes of each returned row. But if this is a list of posts for navigation purposes, I want them ordered so that the most recent post is first. I can add order to the Find All options hash and give it a string of "Created at desc" for descending.

[01:17] Because I'm using Post JS and "Created at" has an upper-case letter, I need to wrap it in double quotes. Running Find JS now gives me the posts in order from newest to oldest. But what if I don't want all of the attributes? For a navigation list, I may only need the ID and Title attributes. Find All provides a simple way to limit the attribute's return just by adding an attributes array to the options hash passed into it. I'll specify ID and title.

[01:51] Now when I run Find, the output only includes ID and title for each post instance.

egghead
egghead
~ 32 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today