지난 포스팅에서 우리는 comment에 임의의 id를 부여했다. 이렇게 임의로 아이디를 부여하게 되면 별로 좋은 방법이 아니라는 것을 알 것이다. 이런 경우를 위해 사용하는 패키지
UUID
를 사용해보도록 하자.
UUID는 유니크한 ID를 생성해주는 패키지라고 생각하면 된다. 설치는 다음과 같이 진행하자
npm i uuid
const { v4 : uuid} = require('uuid');
const comments = [
{
id : uuid(),
username : 'Todd',
comment : 'lol that is so funny !'
},
{
id : uuid(),
username : 'Skyler',
comment : 'I like to go birdwatching with my dog'
},
{
id : uuid(),
username : 'Sk8erBoi',
comment : 'Plz delete your account, Todd'
},
{
id : uuid(),
username : 'onlysayswoof',
comment : 'woof woof woof !!'
}
]
app.post('/comments', (req,res) => {
const {username, comment} = req.body;
comments.push({id: uuid(), username, comment});
res.redirect('/comments');
})
다음과 같이 v4를 uuid라는 이름의 변수로 전환해준뒤에 comment 내부의 id에 uuid()를 사용해주면 고유한 id를 부여해준다. 이전에 새로 등록하는 Post에 대해서도 고유 id를 부여할 수 있도록 id:uuid()를 추가하자.
--> 다음과 같이 해당 comment의 고유 id가 출력된다.