DB/MySQL

MySQL | CRUD with Node.js | Update and Delete

개발자티포 2021. 12. 9. 21:33
728x90
반응형

전 포스트까지 Create, Find api를 만들었다. 이번엔 마지막으로 수정과 삭제를 구현해보겠다.

 

1. Update 라우터를 만들어준다.

routes/index.js

...

router.patch('/update', async (req, res, next) => {
    const query = req.query; // 클라이언트에서 보낸 query
    const where = JSON.parse(query.where); // 수정할 튜플 검색 (ex. {"name" : "teepo"})
    const content = JSON.parse(query.content); // 수정할 내용 (ex. {"email" : "teepo3@co.kr"})

    Users.update(content, { where }) // 검색 조건이 있을 경우 조건에 맞게 데이터를 수정한다.
        .then((result) => {
            console.log("수정 성공: ", result);
            return res.send({ success: true });
        })
        .catch((err) => {
            console.log("수정 Error: ", err);
            return res.send({ success: false });
        });
});

...

 

2. postman으로 확인해본다. ( email이 teepo@co.kr 인 튜플의 email을 teepo3@co.kr로 바꾸어본다. )

 

3. HeidiSQL로 확인해본다.

이메일이 정상적으로 바뀌었다.

 

 

4. Delete 라우터를 만든다.

routes/index.js

...

router.delete('/delete', async (req, res, next) => {
    const query = req.query; // 클라이언트에서 보낸 query
    Users.destroy({ where: query }) // 검색 조건이 있을 경우 조건에 맞게 데이터를 삭제한다.
        .then((result) => {
            console.log("삭제 성공: ", result);
            return res.send({ success: true });
        })
        .catch((err) => {
            console.log("삭제 Error: ", err);
            return res.send({ success: false });
        });
});

...

 

5. postman으로 확인해본다. ( email이 teepo2@co.kr 인 튜플을 삭제한다. )

 

6. HeidiSQL로 확인해본다.

 

 

여기까지 우리는 NodeJS 백엔드로 Sequelize를 사용한 CRUD API를 구현해보았다.

728x90
반응형