1. 시퀄라이즈 ORM 이란?
- Object Relational Mapping: 객체와 데이터를 매핑 (1:1 짝지음)
- MySQL 외에도 다른 RDB(Maria, Postgre, SQLite, MSSQL)와도 호환됨.
- 자바스크립트 문법으로 데이터베이스 조작 가능
요약하자면 자바스크립트 문법으로 데이터베이스 조작이 가능하며, 데이터베이스의 데이터를 자바스크립트의 객체로 받아올 수 있다.(매핑)
2. Sequelize 설정 및 DB 연결 절차
2.1. package.json 추가 및 필요한 패키지 설치
npm install express morgan nunjucks sequelize sequelize-cli mysql2
sequelize, sequelize-cli, mysql2 세 가지 패키지를 설치한다.
- mysql2는 MySQL과 Node.js 간의 드라이버, DB가 아님.
- 하나의 Node 애플리케이션에서 여러 개의 DB에 연결 가능
2.2. Sequelize 초기화
npx sequelize init
위의 명령어는 'sequelize-cli' 로부터 나온 명령어로 sequelize를 초기화할 수 있도록 한다.
Sequelize CLI [Node: 23.6.0, CLI: 6.6.2, ORM: 6.37.5]
Created "config/config.json"
Successfully created models folder at "/Users/h2k/JavaScript/Inflearn/9_sequelize/models".
Successfully created migrations folder at "/Users/h2k/JavaScript/Inflearn/9_sequelize/migrations".
Successfully created seeders folder at "/Users/h2k/JavaScript/Inflearn/9_sequelize/seeders".
2.3. models/index.js 수정
const Sequelize = require('sequelize');
const env = process.env.NODE_ENV || 'development';
const config = require('../config/config')[env];
const db = {};
const sequelize = new Sequelize(config.database, config.username, config.password, config);
db.sequelize = sequelize;
module.exports = db;
2.4. config/config.json 수정
{
"development": {
"username": "root",
"password": "******", //mysql root 비밀번호 입력
"database": "nodejs", //연결할 스키마 입력
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
development 내의 'password' 와 'database' 항목만 수정한다.
2.5. app.js 수정
const express = require('express');
const path = require('path');
const morgan = require('morgan');
const nunjucks = require('nunjucks');
const { sequelize } = require('./models');
// const indexRouter = require('./routes');
// const usersRouter = require('./routes/users');
// const commentsRouter = require('./routes/comments');
const app = express();
app.set('port', process.env.PORT || 3001);
app.set('view engine', 'html');
nunjucks.configure('views', {
express: app,
watch: true,
});
sequelize.sync({ force: false })
.then(() => {
console.log('데이터베이스 연결 성공');
})
.catch((err) => {
console.error(err);
});
app.use(morgan('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use('/', indexRouter);
// app.use('/users', usersRouter);
// app.use('/comments', commentsRouter);
app.use((req, res, next) => {
const error = new Error(`${req.method} ${req.url} 라우터가 없습니다.`);
error.status = 404;
next(error);
});
app.use((err, req, res, next) => {
res.locals.message = err.message;
res.locals.error = process.env.NODE_ENV !== 'production' ? err : {};
res.status(err.status || 500);
res.render('error');
});
app.listen(app.get('port'), () => {
console.log(app.get('port'), '번 포트에서 대기 중');
});
sequelize.sync 하는 부분이 sequelize가 데이터베이스에 접근해 연결하는 로직이다.
- Error: connect ECONNREFUSED 127.0.0.1:3306 : MySQL 서버가 실행되지 않음
- Error: Access denied for user 'root'@'localhost' (using password: YES) : 비밀번호 오류
- Error: Unknown database : 데이터베이스 존재하지 않음
2.7. DB 연결 성공
'Node.js' 카테고리의 다른 글
데이터베이스 - 테이블 관계 (0) | 2025.01.17 |
---|---|
데이터베이스 - 시퀄라이즈 모델 (0) | 2025.01.17 |
데이터베이스 - MySQL CRUD 작업하기 (0) | 2025.01.16 |
데이터베이스 - MySQL 테이블 생성 (0) | 2025.01.16 |
데이터베이스 - MySQL 설치 (0) | 2025.01.16 |