[node.js] 시퀄라이즈 (Sequelize) 사용하기
시퀄라이즈(Sequelize)란?
시퀄라이즈는 DB 작업을 쉽게 할 수 있도록 도와주는 라이브러리이다. ORM(Object-relational Mapping)으로 분류되며, ORM은 자바스크립트 객체와 데이터베이스의 릴레이션을 매핑해주는 도구이다.
시퀄라이즈는 자바스크립트 구문을 알아서 SQL로 바꿔준다. 따라서 SQL 언어를 직접하용하지 않고 MySQL을 조작할 수 있다.
package.json
{
"name": "learn-sequelize",
"version": "0.0.1",
"description": "시퀄라이즈를 배우자",
"main": "app.js",
"scripts": {
"start": "nodemon app"
},
"author": "newjeans",
"license": "MIT"
}
시퀄라이즈에 필요한 sequelize와 sequelize-cli, mysql2 패키지를 설치
npm i express morgan sequelize sequelize-cli mysql2
npm i -D nodemon
sequelize-cli : 시퀄라이즈 명령어를 실행하기 위한 패키지
mysql2 : MySQL과 시퀄라이즈를 이어주는 드라이버
설치 완료 후 sequelize init명령어를 호출
npx sequelize init
명령어를 호출하면 config, models, migrations, seeders폴더가 생성된다.
models 폴더 안에 index.js 폴더를 수정해주자
index.js
const Sequelize = require('sequelize');
const env = process.env.NODE_ENV || 'development';
const config = require('/../config/config.json')[env];
const db = {};
const sequelize = new Sequelize(config.database, config.username, config.password, config);
db.sequelize = sequelize;
module.exports = db;
Sequelize : 시퀄라이즈 패키지이자 생성자.
config/config.json에서 데이터베이스 설정을 불러온 후 new Sequelize를 통해 MySQL 연결 객체를 생성한다. 연결 객체를 나중에 재사용하기 위해 db.sequelize에 넣어둔다.
1. MySQL 연결하기
시퀄라이즈를 통해 익스프레스 앱과 MySQL을 연결해보자
app.js
const express = require('express');
const path = require('path');
const morgan = require('morgan');
const nunjucks = require('nunjucks');
const { sequelize } = require('./models');
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((req, res, next) => {
const error = new Error(`${req.method} ${req.url} 라우터가 없습니다.`);
error.status = 404;
});
app.use((err, req, res, next) => {
res.locals.massage = err.message;
res.locals.error = process.env.NODE_ENV !== 'production' ? err : {};
res.status(err.static || 500);
res.render('error');
});
app.listen(app.get('port'), () => {
console.log(app.get('port'), '번 포트에서 대기 중');
});
require('./models')는 require('./models/index.js')와 같다. 폴더 내 index.js 파일은 require할 때 이름을 생략할 수 있다.
db.sequelize를 불러와서 sync 메서드를 사용해 서버를 실행할 때 MySQL과 연동되도록 했다.
MySQL과 연동할 때는 config 폴더 안의 config.json 정보가 사용된다.
자동으로 생성된 config.json에 operatorAliases 속성이 있다면 삭제한다
config/config.json
{
"development": {
"username": "root",
"password": "[root 비밀번호]",
"database": "nodejs",
"host": "127.0.0.1",
"dialect": "mysql"
},
development.password와 development.database를 현재 MySQL 커넥션과 일치하게 수정한다
아래 test와 production은 설정하지 않는다.
$ npm start
> learn-sequelize@0.0.1 start
> nodemon app
[nodemon] 2.0.22
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
3001 번 포트에서 대기 중
Executing (default): SELECT 1+1 AS result
데이터베이스 연결 성공
마지막 두로그가 뜨면 연결이 성공한 것이다.
참고 : ⌜node.js 교과서⌟ 책을 공부하며 요약・정리한 내용입니다.