다른 부분은 4주차에 했던 것을 응용하여 했으나, 삭제는 어떻게 내가 지우는 데이터가 DB에서도 정확하게 삭제되게 하지? 에 대해 고민을 많이 했다.
시도1: 숫자를 1부터 차례대로 부여하면 되지 않을까?
// 전역변수 let id = 0;
function makeTodo() {
id++;
const todo_give = document.querySelector('.input-text').value;
fetch('/todo/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: todo_give,
id: id
}),
})
.then(response => response.json())
.then(data => {
alert(data['msg']);
window.location.reload();
})
}
결과: 창이 새로고침 될 때마다 처음부터 다시 읽기 때문에 모든 id가 결국 1이 된다(실패)
시도2: DB에 있는 objectid를 사용하면 되지 않을까?
mongoDB는 각 요소 하나 하나가 id를 가지고 있다. 이를 이용해서 이 id 값을 사용할 수 있을까 싶어 구글링을 한 결과 bson 패키지를 이용하면 쓸 수 있겠다는 생각이 들어 패키지를 다운로드 헀다!
그러나 매개변수 오류라는 메세지와 함께 패키지를 받을 수 없었다...(실패)
시도3: 내가 id를 만들자!
function makeTodo() {
const todo_give = document.querySelector('.input-text').value;
const id_give = Math.random().toString(36).substr(2,11);
fetch('/todo/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: todo_give,
id: id_give
}),
})
.then(response => response.json())
.then(data => {
alert(data['msg']);
window.location.reload();
})
}
여기에 있는 todo_give 변수에 무작위로 생성된 10자를 DB로 보내서 구분을 지었더니 성공했다!!
+)기능은 구현하였으나... 디자인을 어떻게 보기 좋게 하는지 잘 모르겠따
+)fetch 기능을 잘 활용하면 새로고침 없이 만드는 것 또한 가능할 텐데 아직 방법을 잘 모르겠다...ㅠㅠ