Sequelize has a powerful query mechanism, this lesson teaches the basics of querying using the
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.
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.
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.
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.
Now when I run Find, the output only includes ID and title for each post instance.