Getting Started with Sequelize in Node.js: A Complete Guide with Code Examples

Introduction

Sequelize is an Object-Relational Mapping (ORM) library for Node.js that simplifies database interactions by allowing developers to use JavaScript code instead of SQL. With Sequelize, you can easily create, read, update, and delete data from a database using JavaScript code. Sequelize supports multiple databases, including MySQL, PostgreSQL, SQLite, and MSSQL.

In this blog, we will discuss how to use Sequelize in a Node.js application. We will create a simple Node.js application that will interact with a MySQL database using Sequelize. We will cover the following topics:

  1. Setting up a Node.js project with Sequelize
  2. Defining database models with Sequelize
  3. Creating database tables with Sequelize
  4. Reading data from a database with Sequelize
  5. Updating data in a database with Sequelize
  6. Deleting data from a database with Sequelize

Setting up a Node.js project with Sequelize

To get started with Sequelize, we need to create a new Node.js project and install the Sequelize library. We can use the Node Package Manager (npm) to create a new project and install the Sequelize library. Open your terminal and run the following commands:

mkdir node-sequelize-example
cd node-sequelize-example
npm init -y
npm install sequelize mysql2

The above commands will create a new directory called node-sequelize-example, initialize a new Node.js project with default settings, and install the Sequelize library and the MySQL2 driver.

Defining database models with Sequelize

After setting up the Node.js project, we can define the database models using Sequelize. A model is a JavaScript class that represents a database table. We can define a model using the sequelize.define() method. The sequelize.define() method takes two arguments:

  1. The name of the model
  2. An object that defines the columns of the model and their data types

Let’s define a model for a users table with the following columns:

  1. id – an auto-incrementing integer primary key
  2. name – a string
  3. email – a string

Create a new file called models/User.js and add the following code:

const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');

const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  }
});

module.exports = User;

In the above code, we first import the DataTypes and the sequelize instance from the ../config/database module. We then define a new User model using the sequelize.define() method. The model has three columns: idname, and email. The id column is an auto-incrementing integer primary key. The name and email columns are strings and are required.

Creating database tables with Sequelize

After defining the models, we need to create the database tables using Sequelize. We can use the sequelize.sync() method to create the tables. The sequelize.sync() method will create the tables if they do not exist in the database.

Create a new file called config/database.js and add the following code:

const { Sequelize } = require('sequelize');

const sequelize = new Sequelize('mysql://root:@localhost:3306/node-sequelize-example');

module.exports = sequelize;

In the above code, we create a new sequelize instance and connect it to a MySQL database running on localhost with the name node-sequelize-example. Replace the connection string with your own database connection string if necessary.

Now, we can create the database tables by running the following script:

const sequelize = require('./config/database');
const User = require('./models/User');

(async () => {
  try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');
    await sequelize.sync({ force: true });
    console.log('All models were synchronized successfully.');
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }
})();

In the above code, we first import the sequelize instance and the User model. We then authenticate the connection to the database using the sequelize.authenticate() method. If the authentication is successful, we create the database tables using the sequelize.sync() method. The { force: true } option will drop the existing tables and recreate them if theyalready exist.

Reading data from a database with Sequelize

Now that we have created the database tables, we can read data from the database using Sequelize. We can use the Model.findAll() method to retrieve all records from a table. The Model.findOne() method can be used to retrieve a single record from a table. We can also use the Model.findByPk() method to retrieve a record by its primary key.

Let’s create a new file called index.js and add the following code to retrieve all the User records from the database:

const sequelize = require('./config/database');
const User = require('./models/User');

(async () => {
  try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');
    const users = await User.findAll();
    console.log(users);
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }
})();

In the above code, we first import the sequelize instance and the User model. We then authenticate the connection to the database using the sequelize.authenticate() method. If the authentication is successful, we retrieve all the User records from the database using the User.findAll() method. The retrieved records are stored in the users variable, which we log to the console.

Updating data in a database with Sequelize

We can also update data in the database using Sequelize. We can use the Model.update() method to update records in a table. The Model.update() method takes two arguments:

  1. An object that contains the new values for the columns
  2. An object that specifies the filter criteria for the records to be updated

Let’s update the name of a user with the email example@email.com. Add the following code to the index.js file:

const sequelize = require('./config/database');
const User = require('./models/User');

(async () => {
  try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');
    const user = await User.findOne({ where: { email: 'example@email.com' }});
    console.log(user);
    await user.update({ name: 'John Doe' });
    console.log(user);
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }
})();

In the above code, we first retrieve the User record with the email example@email.com using the User.findOne() method. We then update the name column of the retrieved record to John Doe using the user.update() method. We log the record before and after the update to the console.

Deleting data from a database with Sequelize

Finally, we can delete data from the database using Sequelize. We can use the Model.destroy() method to delete records from a table. The Model.destroy() method takes an object that specifies the filter criteria for the records to be deleted.

Let’s delete a user with the email example@email.com. Add the following code to the index.js file:

const sequelize = require('./config/database');
const User = require('./models/User');

(async () => {
  try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');
    const user = await User.findOne({ where: { email: 'example@email.com' }});
    console.log(user);
    await user.destroy();
    console.log(user);
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }
})();

In the above code, we first retrieve the User record with the email example@email.com using the User.findOne() method. We then delete the retrieved record using the user.destroy() method. We log the record before and after the deletion to the console.

Conclusion

In this blog, we have learned how to use Sequelize in a Node.js application to interact with a MySQL database. We have covered how to define database models, create database tables, read data from a database, update data in a database, and delete data from a database using Sequelize. We hope that this guide has helped you understand how to use Sequelize in your Node.js projects.

Comments

  1. Pingback: Node.js Development: Friendly Introduction to Creating a Simple Server - Share Your Knowledge

  2. Beauty

    you’re really a good webmaster. The web site loading speed is incredible. It seems that you are doing any unique trick. Also, The contents are masterwork. you have done a wonderful job on this topic!

  3. Post
    Author

Leave a Reply

Your email address will not be published. Required fields are marked *