Nomad-Wetube-6) Database -1

이은지·2023년 2월 15일
0

풀스택 유튜브 클론코딩 강의 #6.0 ~ 6.14 (230217)

1. Array database

1) 각 비디오 페이지의 링크는 id를 가진다

[video.pug]
a(href=`/videos/${video.id}`)=video.title

2) id를 가져와서, id에 해당하는 비디오를 찾아서 렌더링 해준다

[videoController.js]
const { id } = req.params; //id 가져오기
const video = videos[id - 1]; //배열의 index는 0부터 시작하기 때문에 원하는 인덱스를 찾으려면 -1 해주기
res.render("watch", { pageTitle: `Watching ${video.title}` });

3) video의 타이틀 수정

[videoController.js]
const { id } = req.params;
const { title } = req.body; //수정한 video title 가져오기
videos[id - 1].title = title; //수정한 title로 업데이트 하기
return res.redirect(`/videos/${id}`); //watch 페이지로 되돌아가기
  • id 가져오기
const { id } = req.params;
const id = req.params.id;
const {params : { id },} = req;
//전부 같음

[Method]

form과 backend 사이의 정보전송에 관한 방식

GET : 데이터를 받을 때 (접근)
POST : 데이터를 보낼 때 (전송)
redirect() : 브라우저가 redirect(자동으로 이동)하도록 하는것

2. Express; req

1) req.params

라우터의 매개변수
예를 들어 /:id/:name 경로가 있으면 ":id"속성과 ":name"속성을 req.params.id, req.params.name으로 사용할 수 있다

// 요청온 url : www.example.com/public/100/jun
router.get('/:id/:name', (req, res, next) => {
  console.log(req.params) // { id: '100', name: 'jun' }
});

2) req.query

경로의 각 쿼리 문자열 매개 변수에 대한 속성이 포함 된 개체 (주로 GET 요청에 대한 처리)
예를 들어 www.example.com/post/1/jun?title=hello! 이면, title=hello! 부분을 객체로 매개변수의 값을 가져온다.

[클라이언트]
await axios({
  method: "get",
  url: `www.example.com/post/1/jun`,
  params: { title: 'hello!' },
})

[서버]
// 요청온 url : www.example.com/public/100/jun
router.get('/:id/:name', (req, res, next) => {
  console.log(req.query) // { title : 'hello!' }
});

3) req.body

JSON 등의 바디 데이터를 담을때 사용, 기본적으로는 undefined이며 express.json() 또는 express.urlencoded()와 같은 바디 파싱 미들웨어를 사용할 때 값을 받아옴

[클라이언트]
await axios.post('www.example.com/post/1/jun', { 
    name: 'nomad', // post 로 보낼 데이터
    age: 11,
    married: true
});

[서버]
router.get('/:id/:name', (req, res, next) => {
  // post보낼때 담은 객체 부분이 담기게 된다.
  console.log(req.body) // { name: 'nomad', age: 11, married: true }
});
  • app.use(express.urlencoded({ extended: true }));
    //express application이 form의 value들을 이해할 수 있게 하고, 우리가 쓰는 JS형식으로 바꾸게 함!

3. MongoDB 설치하기

[경고문]

[MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.

[해결][db.js]

mongoose.set("strictQuery", false); //이부분 추가
mongoose.connect("mongodb://127.0.0.1:27017/Newtube", {
  useNewUrlParser: true,
  useUnifiedtopology: true,
});

CRUD

  • Create(생성), Read(읽기), Upload(수정), Delete(삭제)

4. Callback, Promise

video.find({"요게 끝나면"},이거가 실행)
//{} => search terms , 비어있으면 모든형식을 찾는다는걸 의미한다
[videoController.js callback 방식]
export const home = (req, res) => {
  Video.find({}, (error, videos) => {
  return res.render("home", { pageTitle: "Home", videos });
  });
};
[videoController.js promise 방식]
export const home = async(req, res) => {
  const videos = await Video.find({}); //await을 적으면 database에게 결과값을 받을 때까지 기다려줌
  Video.find({});
  return res.render("home", { pageTitle: "Home", videos });
};

callback 장점 : 에러들을 바로 볼 수 있지만 function안에 function이 계속 중첩되면 지저분해 보일 수 있고 유지보수가 힘들다
async await : 매우 직관적이고, js가 어디서 어떻게 기다리는지 알 수 있다. error가 어디서 오는지 명확하지 않아서 try catch를 사용

5. return, render

return의 역할 : function을 마무리짓는 역할로 사용. 즉, 에러방지!

  • 템플릿을 렌더링하려면 항상 res.render를 호출하고 return 하지않아도 된다
  • render한 것은 다시 render 할 수 없다.

0개의 댓글