Language: EN

como-usar-sequalize-con-nodejs

How to use Sequalize with Node.js

Sequelize, a popular ORM in the Node.js community. It significantly simplifies 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.

Connecting 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 driver

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 connection to the database 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',
});

Model Definition

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,
  },
});

Synchronize and Use the Model

Finally, we synchronize the model with the database and perform operations such as creating, querying, 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: 'John',
    age: 25,
    email: 'john@example.com',
  });
  
  console.log('User created:', newUser.toJSON());
  
  // Query users
  const users = await User.findAll();
  console.log('Users found:', users.map(u => u.toJSON()));
  
  // Update user
  await User.update({ age: 30 }, { where: { name: 'John' } });
  
  // Delete user
  await User.destroy({ where: { name: 'John' } });
})();

CRUD Operations

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

Data Creation

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

Data Reading

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

Data Update

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

Data Deletion

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