An elegant guide to Sequelize and Node.js

Sequelize is a promise-based SQL ORM for Node.js, with support to Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL!
During this tutorial, we will go through the creation of a simple library database using Sequelize and Node.js system.

What You Will Learn#

  • How to do CRUD SQL operations with Sequelize ✅

  • To create your own Sequelize models ✅

  • Use Sequelize to handle model relationships ✅

Requirements#

Create a model to represent our first table#

Models are the soul of Sequelize, we use them to represent the data of our tables, both on a row-level as a model instance, or as a table structure level as a model.
Let's create our first model to represent a book in our library.

But first using NPM we need to install the following libraries:

Let's create a db.js file, to initialize our Sequelize database connection

Now, let's create a book.js file to store our model

In the previous model, we only defined the model name as 'Book', but when we create the table in the database is gonna be named "Books", this is because when a table name is not specified, Sequelize table name inference, uses the library inflection to pluralize the model name, and apply it as the table name.


Now let's add an index.js file to serve as our application entry point. Here we will have a main function that we will use to create our first object in the database.

The following line would be dangerous in a real-life application

await sequelize.sync({ alter: true });

In a production environment, this could cause major data loss, you should be careful with it, the proper way of doing data migrations using Sequelize is through the migrations procedures.

Using our model to do more CRUD operations#

Let's have some fun with some crud operations inside our main function.

Let's list all the books in our database:

Here is the data I got in my DB after running the findAll query:

To delete an entry in the database, we use .destroy() method:

If you wanted to delete all the elements in a table you would do:

await Book.destroy({ truncate: true })

Any call to the destroy method without truncate: true, or a where clause will result in an error.

To update a model we use .update() method:

To drop an entire table, we would use the .drop() method:

Indexes and performance for our queries#

The way we index our data in our database is essential for the functionality of our system, a good index will allow you to properly retrieve data faster, for example, the 2 following queries, gets us the same data

The difference is that, since the latter is using the primary Key index, to search for the element will be faster.

Model Relationships#

Models can relate to each other. Let's say we have an author model that relates to the book model where a book could have a single author and an author could have multiple books.

Let's create the Author.js file:


And we need to update our Book.js file in the following manner to include the authorId foreign key:

These are one too many relations. In Sequelize we use the method .belongsTo() and .hasMany() to properly define the relation.

In our index.js lets do the following:

One too many relations require for the existence of a third table, for indexing purposes, we can automatically create such a table by passing an inexistent table name when calling the .belongsTo() method:

Book.belongsTo(Author, { through: 'bookAuthorKeys'});

Conclusion#

We've been through a lot within this short post but with these few examples, you should have a good grasp on the core functionalities of Sequelize.

Sequelize is a really potent tool for working with SQL databases from within Node.js. If you want to keep going deeper into it, I recommend following it up with learning about Sequelize transactions and migrations.

Have fun and keep coding!

More Resources#

Check out the documentation of the modules we used in this post:

Getting Help (and Feedback)#

If you have any questions - or want feedback on your post - come join our community Discord. See you there!