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. 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 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. 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: To update a model we use .update() method: To drop an entire table, we would use the .drop() method: 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. 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: 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! Check out the documentation of the modules we used in this post: If you have any questions - or want feedback on your post - come join our community Discord . See you there!