본문 바로가기
기타 프로그램

Node.js DB 데이터 추가, 수정, 삭제

by 고체물리학 2022. 2. 28.

2022.02.28 - [기타 프로그램] - Node.js seed 데이터 넣기, 모델과 테이블 연동, 정보 조회( findAll ,findOne)

이전 포스팅에 이어서...

row 추가하기

 

app.js

app.post('/api/members', async (req, res) => {
    const newMember = req.body;
    const member = Member.build(newMember);
    await member.save();
    res.send(member);
});

test.http

POST http://localhost:3000/api/members
Content-Type: application/json

{
    "id": 3,
    "name":"Kim",
    "team": "enginnering",
    "position":"Android Developer",
    "emailAddress": "kim@enginnering.com",
    "phoneNumber": "010-1234-5678",
    "admissionDate":"2021/02/25",
    "birthday":"1995/01/01",
    "profileImage": "profileImage3.png"

}

id 3번이 잘 추가된 것을 알 수 있다

 

추가할 때 id 속성을 주지 않아도 자동으로 증가해서 추가된다

 

위의 코드 build + save 대신 create 메서드 사용 가능

app.post('/api/members', async (req, res) => {
  const newMember = req.body;
  const member = await Member.create(newMember);
  res.send(member);
});

 

row 수정하기

 

방금 넣었던 id 3의 position을 수정해본다

app.js

app.put('/api/members/:id', async (req, res) => {
    const {id} = req.params;
    const newInfo = req.body;
    const result = await Member.update(newInfo,{where: {id}});
    if(result[0]){
        res.send({message: `${result[0]} row(s) affected`});
    }else{
        res.status(404).send({message: 'There is no member with the id'});
    }

});

test.http

PUT http://localhost:3000/api/members/3
Content-Type: application/json

{
    "position": "IOS Developer"

}

 

수정하는 다른 방법

app.put('/api/members/:id', async (req, res) => {
    const {id} = req.params;
    const newInfo = req.body;
    const member = await Member.findOne({where:{id}});
    if (member){
        Object.keys(newInfo).forEach((prop)=>{
            member[prop] = newInfo[prop];
        });
        await member.save();
        res.send(member);
    }else{
        res.status(404).send({message: 'There is no member with the id'});
    }

})

 

row 삭제하기

app.js

app.delete('/api/members/:id', async (req, res)=>{
    const {id} = req.params;
    const deleteCount = await Member.destroy({where:{id}});
    if (deleteCount){
        res.send({message: `${deleteCount} row(s) deleted`});
    }else{
        res.status(404).send({message: 'There is no member with the id'});
    }
});

또는

app.delete('/api/members/:id', async (req, res) => {
  const { id } = req.params;
  const member = await Member.findOne({ where: { id } });
  if (member) {
    const result = await member.destroy();
    res.send({ message: `1 row(s) deleted` });
  } else {
    res.status(404).send({ message: 'There is no member with the id!' });
  }
});

 

반응형

댓글