This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Sequelize: Querying Basics using findAll

    Mike FreyMike Frey

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

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss