Learn how to set up Sequelize ORM with MySQL in your Node.js project. This guide covers configuration, models, and best practices for seamless integration.
Table of content
When developing web applications in Node.js, using an ORM like Sequelize can simplify your interaction with databases. Sequelize is a powerful JavaScript ORM for SQL databases like MySQL, offering an intuitive API to manage your data models and queries. This guide will walk you through setting up Sequelize with MySQL, including basic configuration, model creation, and tips for troubleshooting.
To get started, install the necessary packages in your project directory:
npm install sequelize mysql2
Or with Yarn:
yarn add sequelize mysql2
Create a new file (e.g., database.js
) to handle the database connection.
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'localhost',
dialect: 'mysql',
logging: false, // Disable logging; default: console.log
});
module.exports = sequelize;
Tips:
database_name
, username
, and password
with your MySQL credentials.Always test your connection before moving forward:
const sequelize = require('./database');
(async () => {
try {
await sequelize.authenticate();
console.log('Connected to MySQL database successfully!');
} catch (error) {
console.error('Unable to connect:', error);
}
})();
Let’s create a sample model (e.g., User
model) in a models/user.js
file:
const { DataTypes } = require('sequelize');
const sequelize = require('../database');
const User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
});
module.exports = User;
Synchronize your models with the MySQL database:
const sequelize = require('./database');
const User = require('./models/user');
(async () => {
await sequelize.sync({ force: true }); // Use force: false in production
console.log('All models were synchronized!');
})();
By following these steps, you can set up Sequelize with MySQL for your Node.js projects efficiently. Sequelize empowers you to build scalable web applications while keeping your codebase clean and maintainable. For more tips and advanced configurations, refer to the official Sequelize documentation.