본문 바로가기
Back-End/🌿Express (nodeJS)

[Express] Sequelize로 MySQL 연결하기 (2) - CRUD 작업

by 코딩하는 동현😎 2022. 11. 8.

Sequelize 라이브러리

시퀄라이즈는 ORM의 한 종류입니다.

ORM은 객체와 데이터베이스의 릴레이션(명령어)를 매핑해주는 도구입니다.

쉽게 말해서 자바스크립트 객체를 ORM함수로 입력하면 ORM이 MySQL 명령어로 변역해서 실행해주는 것입니다.

꼭 mysql뿐만 아니라 다른 데이터베이스 언어와도 전부 호환 됩니다.

 

npm으로 설치

sequelize-cli는 (comand line interface)로 시퀄라이즈 명령어를 터미널로 실행하기 위한 패키지이고, mysql2는 MySQL과 ORM을 연결해주는 드라이버입니다.

mysql2이랑 MySQL이랑 헷갈리면 안됩니다. 별도로 설치해야합니다.

npm i express sequelize sequelize-cli mysql2

 

Sequelize 초기화

아래의 명령어를 실행해주면 config, models, migrations, seeders 폴더가 자동 생성됩니다

npx sequelize init

CRUD 작업

CRUD란 Create, Read, Update, Delete을 의미합니다.

객체를 생성하고 조회하고 수정하고 삭제한다는 의미입니다.

보통 SQL에서는 Create는 INSERT , Read는 SELECT,  Update 는 UPDATE로, Delete는 DELETE 명령어로 수행합니다.

 

요청을 받았을때 어떻게 js으로 데이터베이스를 다루는지 알아보겠습니다.

 

이전 포스트 ([Express] Sequelize로 MySQL 연결하기 (1))에 있는 프로젝트 그대로 설명하겠습니다.


User 객체 생성하기

 

router/users.js

 

아래 SQL 코드와 같은 효과 입니다.

INSERT INTO `users` (name, age, married) VALUES (req.body.name, req.body.age, req.body.married)

 

const User = require('../models/user');

router.post('/' ,async (req, res, next) =>{
    try {
        const user = await User.create({
            name : req.body.name,
            age : req.body.age,
            married : req.body.married,
        })
        console.log(user);
        res.status(201).json(user);
    } catch (error) {
        console.error(error);
        next(error)
    }
})

/users 으로 유저의 정보를 POST 형식으로 요청을 보내면 그 객체를 데이터베이스에서 추가하는 코드입니다.

당연히 users의 데이터베이스를 다루려면 테이블 객체를 불러와야겠죠? (User = require('../models/user'))

 

테이블 객체(User) 의 create 함수를 이용해서 각 속성들을 입력해서 생성해줍니다.


User 객체 조회하기

SQL문 과 기본적인 함수는 아래와 같습니다.

SELECT * FROM users;
User.findAll({})

SELECT * FROM users LIMIT 1;
User.findOne({})

 

where을 이용해서 조회하기 

SELECT * FROM users WHERE age = 20;
User.findAll({
	where : {
    	age : 20
    }
})

SELECT id,name FROM users age > 20;
User.findAll({
	attributes : [id, name],
    where : {
    	age : { [Op.gt] : 20 }
    }
})

SELECT * FROM users ORDER BY age DESC LIMIT 2;
User.findAll({
    where : {
    	order : [['age', 'DESC']],
        limit : 2
    }
})

관계 쿼리 (JOIN)

저번 포스트에서 users 와 comments 는 hasMany-belongsTo로 연결돼있었습니다.

특정 사용자를 가져오면서(id를 이용해서) 그 사람의 모든 댓글을 불러오고 싶으면 아래와 같이 include 속성을 작성하면 됩니다.

router.get('/:id/comments', async (req, res, next) => {
    try {
      const comments = await Comment.findAll({
        include: {
          model: User,
          where: { id: req.params.id },
        },
      });
      console.log(comments);
      res.json(comments);
    } catch (err) {
      console.error(err);
      next(err);
    }
  });

객체 Update 하기

객체를 수정하는 것은 보통 PATCH요청을 받을때 수행을 주로 합니다.

/comment/id 요청을 받으면 아래 쿼리를 진행시킵니다

id 파라미터로 받은것은 req 객체에 params 속성에 저장됩니다.

UPDATE comments SET comment = req.body.comment WHERE id = req.params.id
router.patch('/:id', async (req, res, next)=>{
    try {
        const result = await Comment.update({
            comment : req.body.comment
        },{
            where : { id : req.params.id }
        })
        res.json(result)
    } catch (error) {
        console.error(error)
        next(error)
    }
})

객체 DELETE 하기

클라이언트의 delete 요청에 보통 쿼리를 넣습니다

DELETE FROM users WHERE id = req.params.id
router.delete('/:id', async (req, res, next)=>{
    try {
        const result = await Comment.destroy({where : {id : req.params.id}})
        res.json(result)
    } catch (error) {
        console.error(error)
        next(error)
    }
})
반응형

댓글