이전에 Video모델에 내용을 추가할때, 다음과 같은 코드를 작성 했었다.
owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "User" },
이때 ref는 어떤 다른 모델과 연결 될 것인가에 대한 참조를 써둔 값이라고 했다. 지금 현재 내 videoController의 watch 컨트롤러(영상을 보여주는 페이지를 렌더링 해주는 컨트롤러) 는 다음과 같다.
export const watch = async (req, res) => {
const id = req.params.id;
const video = await Video.findById(id);
const owner = await User.findById(video.owner);
if (video)
return res.render("watch", { pageTitle: video.title, video, owner });
else
return res.render("404", { pageTitle: "Video Not found" });
}
id를 가져오고, 그 id로 Video 모델에서 찾아내고, 해당 video 변수에는 owner가 있기 때문에( 이것도 ObjectId 형 이다) 이를 통해서 owner를 찾아냈다. 하지만 ref 와 populate를 쓰면 훨씬 간단해진다. 일단 위와 같은 코드일 때 video를 console.log 해보겠다.
video 안에 owner가 있는 것을 볼 수 있다. 하지만 코드를 바꾸어 다음과 같이 쓰고 똑같이 console.log 해보자.
export const watch = async (req, res) => {
const id = req.params.id;
const video = await Video.findById(id).populate("owner");
console.log(video);
if (video)
return res.render("watch", { pageTitle: video.title, video });
else
return res.render("404", { pageTitle: "Video Not found" });
}
owner 객체 전체가 저장되었다. 이제 video를 불러올때 마다 User도 모두 볼 수 있게 되었다. ^^7
'Youtube Clone Coding' 카테고리의 다른 글
webpack (0) | 2022.11.23 |
---|---|
프로필에 영상 리스트 보여주기 (0) | 2022.11.22 |
Video와 User 모델 연결 & 영상 보여주기 (0) | 2022.11.22 |
유저 프로필 페이지 (2) | 2022.11.22 |
영상 파일 업로드 (0) | 2022.11.21 |