DEV Community

Cecelia Martinez
Cecelia Martinez

Posted on • Updated on

Sequelize Basics for Beginners

For those of you not familiar with my coding journey, I graduated the Full-Stack Software Engineering Boot Camp at Georgia Tech in July 2019. I wrote a little about my experience diving into back-end development in my blog post about Express Basics for Beginners, but essentially at the time I found myself confused with overlapping Node, Express, and Sequelize functions in my projects, and wanted to take a deeper look at how these programs work together.

In my first post, I wrote about how to set up a server with Express and write routes to handle REST API processes. I will follow the same format here -- first I'll go over how to set up Sequelize and connect it to your SQL database. In part two of this series, I will cover how to write CRUD (Create, Read, Update, and Delete) queries.

You should already have an understanding of how to create an SQL database and an idea of how tables work, but you definitely don't need to be an expert (I definitely am not!).

Sequelize is an ORM (Object Relational Mapping) tool which allows you to query a database using an object-oriented approach, so it's great for those already familiar with an object-oriented language like JavaScript. It is promise-based, so you should also have some understanding of how Promises work in JavaScript, as well as knowledge of Node. It works with multiple flavors of SQL, including MySQL and Postgres. I used MySQL, so check the Sequelize documentation to make sure the specific query you plan to use works with your database set up.

Set-up and Installation

The only action that needs to take place outside of Sequelize is the actual creation of your database. You don't need to create any tables, but you will need to use either your shell or GUI to create the database, so make sure you do that first.

SQL is fairly syntactic, which is great. If you need a reference for common commands, I'd recommend this resource from W3 Schools. It is also system-agnostic so it works whether you use Postgres, MySQL, SQL Server, etc.

Here is my code:

Enter fullscreen mode Exit fullscreen mode

Like I said, it's pretty syntactic.

The next step is installing Sequelize and accompanying packages in Node. I recommend installing Sequelize-CLI globally so you can use it to configure all your projects. You'll also need to install Sequelize locally, as well as your database system (I'm using mysql2).

npm install -g sequelize-cli
npm install sequelize mysql
Enter fullscreen mode Exit fullscreen mode

Once Sequelize-CLI is installed, run the following command in your project folder to create the config.json file and models folder. We'll discuss how to use these in the next section.

sequelize init:config & sequelize init:models
Enter fullscreen mode Exit fullscreen mode

You should see a message output in your console that a models folder and config.json file has been created. You can also confirm it was successful by checking for the folder/file in your project folder. There should also be an index.js file within the models folder.

screenshot of file structure in VS Code after creation of config folder with config.json file and models folder with index.js

Connecting the Database

Inside the config folder you just created, open the config.json file. This is where you set the variables to access the database you created. For local or practice projects, this is fine, but if you don't want to make your database access information public, look into packages like dotenv that let you set environment variables for local development.

screenshot of config.json file generated by Sequelize

Creating the Models

Inside the models folder you created in the first step, you'll see an index.js file. For the setups I've done, I leave this alone except when I'm using environment variables and am using a config.js file instead. In that case, you'd need to update the file name and possibly location in the index.js file.

The purpose of the models folder is to store the individual model files that correlate to a table in your SQL database. You will use Sequelize syntax to define the column names and data types, as well as any validations or restrictions. For this example, we'll have a model for a 'Post' inside our Blog database. Again, you don't need to create any of these tables in MySQL, Sequelize will create the tables for you based on these models.

Inside a file named post.js, I would type the following code:

module.exports = function(sequelize, DataTypes) {
  var Post = sequelize.define("Post", {
    title: DataTypes.STRING,
    author: DataTypes.STRING,
    content: DataTypes.TEXT,
    pubdate: DataTypes.DATE
  return Post;
Enter fullscreen mode Exit fullscreen mode

These is the meat and potatoes of Sequelize, so I want to break down what is happening here.

If you're familiar with SQL, you may recognize this format as a schema. A schema is what is used to create a table in SQL, setting the column names and data types. What Sequelize does is uses an object-oriented approach to creating these schemas using Javascript-like syntax.

In this file, we are exporting a function that creates a 'Post' object using methods and DataTypes from the Sequelize library that will then be used by Sequelize to create the table in your database AND make sure that any new 'Post' objects match the model set here.

I'd recommend taking a look at the Sequelize documentation on Data Types, as well as which data types work with your version of SQL (Postgres, mySQL, etc.)

Within the models folder, you will need to follow the same process for each table in your database. The index.js file will automatically pull any files in this folder to build out the tables.

Creating the Tables

The final step to getting set up with Sequelize is to push or sync the models you just created to the database to create the tables.

Sequelize has a built-in method for this called sync(). I mentioned earlier that Sequelize is promise-based, and here is one of the instances where that comes in to play. Syncying the database models is an asynchronous process, and you don't want your server to start until the database has been synced.

Because of this, you want to make sure the promise created by sync() resolves before starting your server. If you are using Express for your server, your server.js file would look something like this:

var db = require("./models");

var PORT = 3000;
var app = express();

db.sequelize.sync().then(function() {
  app.listen(PORT, function() {
    console.log("Express is running on port" + PORT);
Enter fullscreen mode Exit fullscreen mode

In this code, you are pulling in the models folder as the variable 'db'. You are then using the built-in sequelize.sync() method followed by a .then() containing the Express function to start your server. This ensures the server starts after the sync has resolved.

Make sure you require the models folder.

Handling Changes to Models

If you come across the need to add a new model or modify an existing model, you will need to re-sync your database. When in development, you can add 'force:true' as a parameter to the sync() method to indicate the database needs to be re-built.

db.sequelize.sync({force: true}).then(function() {
    app.listen(PORT, function() {
        console.log("Express is running on port" + PORT);

Enter fullscreen mode Exit fullscreen mode

This will re-build your database. You will need to ensure you remove it before starting your server again, otherwise the database will keep re-building (this is fine if you don't need persistent data to develop). You will also need to re-seed any development data you are using to your database.

Your database is now connected to your app using Sequelize! Please let me know if you have any suggestions or questions! I am always learning and welcome the feedback. Thanks for reading!

Top comments (2)

sanjayism profile image

One of the best Beginer tutorials for sequelize envirment set and initial understanding. I has solved last 3-4 days requirement in understanding sequelizer. thanks for awasome tutorials.

ceceliacreates profile image
Cecelia Martinez

I'm so glad you found it helpful! I'll be doing more tutorials this coming year :)