Step-by-Step Guide to Connecting Sequelize with Node.js

Step-by-Step Guide to Connecting Sequelize with Node.js

Sequelize is a popular ORM (Object-Relational Mapping) for Node.js, providing an easy way to interact with SQL databases. This guide walks you through setting up and connecting Sequelize with a MySQL (or PostgreSQL) database.

1. Install Dependencies

First, ensure you have Node.js installed. Then, initialize a Node.js project and install the required dependencies:

mkdir sequelize-project && cd sequelize-project
npm init -y
npm install sequelize mysql2 dotenv

If you are using PostgreSQL, install:

npm install sequelize pg pg-hstore dotenv

2. Setup Project Structure

Organize your project as follows:

sequelize-project/
|-- config/
|   |-- database.js
|-- models/
|   |-- index.js
|   |-- user.model.js
|-- .env
|-- app.js
|-- package.json

3. Configure Database Connection

Create a .env file to store database credentials:

DB_HOST=localhost
DB_USER=root
DB_PASS=yourpassword
DB_NAME=mydatabase
DB_DIALECT=mysql  # Change to "postgres" if using PostgreSQL

Now, create config/database.js:

require("dotenv").config();
const { Sequelize } = require("sequelize");

const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
  host: process.env.DB_HOST,
  dialect: process.env.DB_DIALECT,
  logging: false,
});

module.exports = sequelize;

4. Define Models

Create a models/user.model.js file:

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

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

module.exports = User;

5. Sync Database & Test Connection

Create a models/index.js file to manage models:

const sequelize = require("../config/database");
const User = require("./user.model");

const connectDB = async () => {
  try {
    await sequelize.authenticate();
    console.log("Database connected successfully.");
    await sequelize.sync({ alter: true });
    console.log("All models were synchronized successfully.");
  } catch (error) {
    console.error("Database connection failed:", error);
  }
};

module.exports = { sequelize, connectDB, User };

6. Initialize the Connection

Modify app.js to test the connection:

const express = require("express");
const { connectDB, User } = require("./models");

const app = express();
app.use(express.json());

connectDB();

app.post("/users", async (req, res) => {
  try {
    const user = await User.create(req.body);
    res.status(201).json(user);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

app.listen(3000, () => console.log("Server running on port 3000"));

7. Start the Application

Run the application:

node app.js

Test the API using Postman or cURL:

curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com"}'

Conclusion
You've successfully set up Sequelize with Node.js! This guide covered:
Installing Sequelize and setting up a database connection
Creating models
Synchronizing and testing the database

(0) Comments

Leave a comment