1. nodemon

코드가 바뀌면 자동으로 재실행해준다. 이와 비슷한 것으로 forever, supervisor, PM2가 있다.

 

 

2. bluebird

프로미스처럼 시간순서대로 실행하게 해준다.

프로미스를 쓰는 것보다 간단하다.

 

3. express

MVC Framework이다.

라우터기능을 쉽게 쓸 수 있다.

 

4. ejs

Template Engine이다.

header, footer 처럼 코드를 분리하고 싶을 때 사용한다.

 

5. mysql

db를 연결시켜준다. async/await을 편하게 사용하려면 promise-mysql을 쓴다.

가독성보다 최적화를 원한다면 mysql을 사용한다. mysql2도 같이 설치한다.

orm을 사용한다면 sequelize를 사용 하는것이 좋다.

 

6. sequelize

db를 연결하여 자바스크립트 문법으로 실행시키는 orm이다.

 

시퀄라이즈는 ORM(Object-relational Mapping)으로 분류가 된다.

ORM은 자바스크립트 객체와 데이터베이스의 릴레이션을 매핑해주는 도구이다.

 

1. express를 이용해서 새 프로젝트 생성

$ express sequlize_ex --view=pug

 

위에 나온대로 디렉토리를 바꿔준뒤 npm i를 해준다.

$ cd sequelize_ex
$ npm i

 

방금 만든 프로젝트에 sequelize와 mysql2 패키지를 설치한다. 그 후 sequelize 커맨드를 사용하기 위해 sequelize-cli를 전역 설치

$ npm i sequelize mysql2
$ npm i -g sequelize-cli
$ sequelize init

 

그 뒤 파일들을 아래대로 세팅

models/index.js

const path = require('path');
const Sequelize = require('sequelize'); //sequelize 연결

const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
const db = {};

const sequelize = new Sequelize(config.database, config.username, config.password, config);


db.sequelize = sequelize;
db.Sequelize = Sequelize;

//user와 comment 테이블을 연결시킨다.
db.User = require('./user')(sequelize, Sequelize);
db.Comment = require('./comment')(sequelize, Sequelize); 

//테이블 간의 관계를 정의해줌
db.User.hasMany(db.Comment, {foreignKey: 'commenter', sourceKey: 'id'});
db.Comment.belongsTo(db.User, {foreignKey: 'commenter', targetKey: 'id'});

module.exports = db; //db라는 객체에 user와 comment 모델을 담는다.

 

시퀄라이즈를 통해 익스프레스 앱과 MYSQL을 연결한다. app.js에서 추가해준다.

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var commentsRouter = require('./routes/comments');

//추가
var sequelize = require('./models').sequelize;

var app = express();

//추가
sequelize.sync();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/comments', commentsRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

 

번거롭지만 MYSQL에서 정의한 테이블을 시퀄라이즈에서도 정의해야 한다.

기본적으로 모델 이름은 단수형으로 테이블 이름은 복수형으로 사용한다.

 

models/user.js

module.exports = (sequelize, DataTypes) => {
    return sequelize.define('user', {
        name: {
            type: DataTypes.STRING(20),
            allowNull: false,
            unique: true,
        },
        age: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
        },
        married: {
            type: DataTypes.BOOLEAN,
            allowNull: false,
        },
        comment: {
            type: DataTypes.TEXT,
            allowNull: true,
        },
        created_at: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW,
        },
    }, {
        timestamps: false,
    });
};

 알아서 id를 기본 키로 연결하므로 id 컬럼은 적어줄 필요가 없다.

그리고 알아둘 것이 timestamps가 true면 시퀄라이즈는 createdAt과 updatedAt 컬럼을 추가하며 행이 생성 될때와 수정될 때의 시간을 자동으로 입력한다.

 

하지만 여기서는 created_at 컬럼을 직접만들었으므로 timestamps는 false로 하였다.

참고로 paranoid: true 도 많이 사용하는데 이러면 deletedAt이라는 컬럼이 추가되어 행이 삭제 되었을 때 제거하는 대신 deletedAt에 제거된 날짜를 입력한다.

 

실무에서는 데이터베이스 복원을 위하여 데이터 삭제는 왠만해선 하지 않는다. 사이트에서 회원탈퇴해도 같은 아이디로는 재가입할 수 없는 것도 이러한 이치.

 

이 외에도 underscored 옵션을 사용하여 캐멀형식이 아닌 _를 중간에 써주어 created_at 처럼 표기시킬 수도 있다.

 

comment 모델도 만들어 보자.

models/comment.js

module.exports = (sequelize, DataTypes) => {
    return sequelize.define('comment', {
        comment: {
            type: DataTypes.STRING(100),
            allowNull: false,
        },
        created_at: {
            type: DataTypes.DATE,
            allowNull: true,
            defaultValue: DataTypes.NOW,
        },
    }, {
        timestamps: false,
    });
};

 

아까 위에서 index.js에서 보듯이 db라는 객체에 user와 comment 모델을 담아두었다.

models/index.js

const path = require('path');
const Sequelize = require('sequelize'); //sequelize 연결

const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
const db = {};

const sequelize = new Sequelize(config.database, config.username, config.password, config);


db.sequelize = sequelize;
db.Sequelize = Sequelize;

//user와 comment 테이블을 연결시킨다.
db.User = require('./user')(sequelize, Sequelize);
db.Comment = require('./comment')(sequelize, Sequelize); 

//테이블 간의 관계를 정의해줌
db.User.hasMany(db.Comment, {foreignKey: 'commenter', sourceKey: 'id'});
db.Comment.belongsTo(db.User, {foreignKey: 'commenter', targetKey: 'id'});

module.exports = db; //db라는 객체에 user와 comment 모델을 담는다.

db객체를 require하여 User와 Comment 모델에 접근할 수 있다.

 

마지막으로 config.json을 수정하여 mysql 비밀번호를 입력하여 연결시켜준다.

본인은 비밀번호는 12351235로 하였다. 

config/config.json

{
  "development": {
    "username": "root",
    "password": "12351235",
    "database": "nodejs",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "database_production",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  }
}

 

그리고 나머지 html 코딩파일은 아래의 파일을 다운로드 받아서 덮어쓰기 한다.

 

 

learn-sequelize.zip
6.28MB

 

 

그 뒤 npm start를 실행시킨다.

 

localhost:3000으로 들어가면 아래와 같은 페이지가 나타난다.

위에 이름나이를 등록하고 중간에 리스트를 클릭하면 아래에 클릭한 리스트가 나타난다.

 

 

 

 

 

 

 

 

 

 

 

1. Insert 문

SQL문법

INSERT INTO nodejs.users (name, age, married, comment) VALUES ('zero', 24, 0, '자기소개1');

sequelize 문법

const { User } = require('../models')
User.create({
name: 'zero',
age: 24,
married: false,
comment: '자기소개1',
});

 

이하 아래부터는 위는 SQL문 아래는 seq문법이다.

 

 

 

- SELECT * FROM nodejs.users;

- User.findALL({});

 

- SELECT * FROM nodejs.users LIMIT 1;

- User.findOne({});

 

- SELECT name, married FROM nodejs.users;

- User.findALL({

  attributes: ['name', 'married'],

});

 

- SELECT name, age FROM nodejs.users WHERE married =1 AND age > 30;

 

- const { User, Sequelize : {Op}} = require('../models');

User.findAll({

  attributes: ['name', 'age'],

where: {

  married: 1,

age: { [Op.gt]: 30 },

},

});

 

- SELECT id, name FROM users ORDER BY age DESC;

- User.findAll({

  attributes: ['id', 'name'],

order: [[ 'age', 'DESC']],

});

 

- UPDATE nodejs.users SET comment = '바꿀 내용' WHERE id = 2;

- User.update({

  comment: '바꿀 내용',

}, {

  where : { id : 2 },

});

 

- DELETE FROM nodejs.users WHERE id = 2;

- User.destroy({

 where: { id : 2},

});

 

1. mysql installer를 이용하여 mysql connector 설치

 이 때 아이디는 root이며 비밀번호는 우선 12351235로 설정

 

또한 workbench도 같이 설치

 

mysql installer download 링크

https://dev.mysql.com/downloads/file/?id=490394

 

MySQL :: Begin Your Download

The world's most popular open source database

dev.mysql.com

리눅스의 경우 아래를 따른다.

$ sudo apt-get update
$ sudo apt-get install -y mysql-server-5.7
$ mysql_secure_installation

 

 

2. db연결 및 테이블 생성

C:\Program Files\MySQL\MySQL Server 8.0\bin 로 들어가서 mysql 실행

mysql -h localhost -u root -p
Enter password: 12351235
mysql>

 

nodejs 스키마를 생성하고 이 스키마를 사용하겠다는 것을 MySQL에 알림

 

mysql> CREATE SCHEMA nodejs;
Query OK, 1 row affected (0.01 sec)

mysql> use nodejs;
Database changed

 

nodejs 데이터베이스의 users 테이블 생성

아래 코드를 입력한다.

CREATE TABLE nodejs.users(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
age INT UNSIGNED NOT NULL,
married TINYINT NOT NULL,
comment TEXT NULL,
created_at DATETIME NOT NULL DEFAULT now(),
PRIMARY KEY(id),
UNIQUE INDEX name_UNIQUE (name ASC))
COMMENT = '사용자 정보'
DEFAULT CHARSET=utf8
ENGINE=InnoDB;

 

결과

mysql> CREATE TABLE nodejs.users(
    -> id INT NOT NULL AUTO_INCREMENT,
    -> name VARCHAR(20) NOT NULL,
    -> age INT UNSIGNED NOT NULL,
    -> married TINYINT NOT NULL,
    -> comment TEXT NULL,
    -> created_at DATETIME NOT NULL DEFAULT now(),
    -> PRIMARY KEY(id),
    -> UNIQUE INDEX name_UNIQUE (name ASC))
    -> COMMENT = '사용자 정보'
    -> DEFAULT CHARSET=utf8
    -> ENGINE=InnoDB;
Query OK, 0 rows affected, 1 warning (0.07 sec)

 

table 정보 확인

mysql> DESC users;
+------------+------------------+------+-----+-------------------+-------------------+
| Field      | Type             | Null | Key | Default           | Extra             |
+------------+------------------+------+-----+-------------------+-------------------+
| id         | int(11)          | NO   | PRI | NULL              | auto_increment    |
| name       | varchar(20)      | NO   | UNI | NULL              |                   |
| age        | int(10) unsigned | NO   |     | NULL              |                   |
| married    | tinyint(4)       | NO   |     | NULL              |                   |
| comment    | text             | YES  |     | NULL              |                   |
| created_at | datetime         | NO   |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
+------------+------------------+------+-----+-------------------+-------------------+
6 rows in set (0.01 sec)

 

그 뒤, 사용자의 댓글을 저장하는 테이블 생성

아래 코드 입력

CREATE TABLE nodejs.comments (
id INT NOT NULL AUTO_INCREMENT,
commenter INT NOT NULL,
comment VARCHAR(100) NOT NULL,
created_at DATETIME NOT NULL DEFAULT now(),
PRIMARY KEY(id),
INDEX commenter_idx (commenter ASC),
CONSTRAINT commenter
FOREIGN KEY (commenter)
REFERENCES nodejs.users (id)
ON DELETE CASCADE
ON UPDATE CASCADE)
COMMENT = '댓글'
DEFAULT CHARSET=utf8
ENGINE=InnoDB;

 

결과

mysql> CREATE TABLE nodejs.comments (
    -> id INT NOT NULL AUTO_INCREMENT,
    -> commenter INT NOT NULL,
    -> comment VARCHAR(100) NOT NULL,
    -> created_at DATETIME NOT NULL DEFAULT now(),
    -> PRIMARY KEY(id),
    -> INDEX commenter_idx (commenter ASC),
    -> CONSTRAINT commenter
    -> FOREIGN KEY (commenter)
    -> REFERENCES nodejs.users (id)
    -> ON DELETE CASCADE
    -> ON UPDATE CASCADE)
    -> COMMENT = '댓글'
    -> DEFAULT CHARSET=utf8
    -> ENGINE=InnoDB;
Query OK, 0 rows affected, 1 warning (0.06 sec)

테이블명 확인

mysql> SHOW TABLES;
+------------------+
| Tables_in_nodejs |
+------------------+
| comments         |
| users            |
+------------------+
2 rows in set (0.00 sec)

 

워크벤치 GUI를 이용하여 테이블을 만드는 것이 일반적임.

 

3. CRUD 작업하기

CREATE (행 생성)

mysql> INSERT INTO nodejs.users (name, age, married, comment) VALUES ('zero', 24, 0, '자기소개1');
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO nodejs.users (name, age, married, comment) VALUES ('nero', 32, 1, '자기소개2');
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO nodejs.comments (commenter, comment) VALUES (1, '안녕하세요. zero의 댓글입니다.');
Query OK, 1 row affected (0.01 sec)

 

READ (조회)

mysql> SELECT * FROM nodejs.users;
+----+------+-----+---------+-----------+---------------------+
| id | name | age | married | comment   | created_at          |
+----+------+-----+---------+-----------+---------------------+
|  1 | zero |  24 |       0 | 자기소개1 | 2019-11-03 23:00:10 |
|  2 | nero |  32 |       1 | 자기소개2 | 2019-11-03 23:00:44 |
+----+------+-----+---------+-----------+---------------------+
2 rows in set (0.00 sec)
mysql> SELECT * FROM nodejs.comments;
+----+-----------+--------------------------------+---------------------+
| id | commenter | comment                        | created_at          |
+----+-----------+--------------------------------+---------------------+
|  1 |         1 | 안녕하세요. zero의 댓글입니다. | 2019-11-03 23:03:32 |
+----+-----------+--------------------------------+---------------------+
1 row in set (0.00 sec)

 

UPDATE (수정)

mysql> UPDATE nodejs.users SET comment = '바꿀 내용' WHERE id = 2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

 

DELETE (삭제)

mysql> DELETE FROM nodejs.users WHERE id = 2;

 

+ Recent posts