Phone: +91 - 7503630654 Email: warriorsitech@gmail.com
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.
           
        
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 dotenvIf you are using PostgreSQL, install:
npm install sequelize pg pg-hstore dotenvOrganize your project as follows:
sequelize-project/
|-- config/
|   |-- database.js
|-- models/
|   |-- index.js
|   |-- user.model.js
|-- .env
|-- app.js
|-- package.jsonCreate 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 PostgreSQLNow, 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;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;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 };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"));Run the application:
node app.jsTest 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"}'
Leave a comment