Language: EN

como-usar-sequalize-con-nodejs

How to use Sequalize with Node.js

Sequelize is a popular ORM in Node.js projects. It significantly simplifies the interaction with SQL databases (such as MySQL, PostgreSQL, and SQLite).

In this article, we will see how to read a database using Sequelize and MySQL.

How to connect Node.js to SQLite

Let’s start by installing Sequelize

npm install sequelize

Now we can choose different databases using the following drivers:

# install one of the following drivers

npm install mysql2    # for mysql2 (MariaDB / MySQL)
npm install pg        # for pg (PostgreSQL)
npm install sqlite3   # for sqlite3 (SQLite)
npm install tedious    # for tedious (Microsoft SQL Server / Express SQL)
npm install oracledb  # for oracledb (Oracle Database)

Database Connection Configuration

We configure the database connection in our configuration file. We will use Sequelize to manage the connection and interactions with the database.

Here is an example of how to configure the connection with a MariaDB / MySQL database.

const Sequelize = require('sequelize');

// Database connection configuration
const sequelize = new Sequelize('database_name', 'user', 'password', {
  host: 'localhost',
  dialect: 'mysql',
});

Defining a Model

Now, we define a model that represents a table in our database. For example, we can define a User model with properties like name, age, and email:

const User = sequelize.define('user', {
  name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  age: {
    type: Sequelize.INTEGER,
    allowNull: false,
  },
  email: {
    type: Sequelize.STRING,
    allowNull: false,
    unique: true,
  },
});

Synchronizing and Using the Model

Finally, we synchronize the model with the database and perform operations such as creating, retrieving, updating, and deleting records.

(async () => {
  await sequelize.sync({ force: true }); // Synchronize model with the database
  
  // Create a new user
  const newUser = await User.create({
    name: 'Luis',
    age: 25,
    email: 'luis@example.com',
  });
  
  console.log('User created:', newUser.toJSON());
  
  // Retrieve users
  const users = await User.findAll();
  console.log('Users found:', users.map(u => u.toJSON()));
  
  // Update user
  await User.update({ age: 30 }, { where: { name: 'Luis' } });
  
  // Delete user
  await User.destroy({ where: { name: 'Luis' } });
})();

CRUD Operations

Once we have defined our model, we can perform CRUD (Create, Read, Update, Delete) operations on our database using Sequelize.

Creating Data

(async () => {
  await sequelize.sync({ force: true }); // Synchronize model with the database
  
  const newUser = await User.create({
    name: 'Luis',
    age: 25,
    email: 'luis@example.com',
  });
  
  console.log('User created:', newUser.toJSON());
})();

Reading Data

(async () => {
  const users = await User.findAll();
  console.log('Users found:', users.map(u => u.toJSON()));
})();

Updating Data

(async () => {
  await User.update({ age: 30 }, { where: { name: 'Luis' } });
})();

Deleting Data

(async () => {
  await User.destroy({ where: { name: 'Luis' } });
})();

Download the Code

All the code from this post is available for download on Github github-full