[유튜브 클론코딩] 3.12 Searching Videos

2021. 3. 9. 17:15Projects/유튜브 클론코딩

728x90
반응형

3.12 Searching Videos

정규표현식을 사용하여 Search 구현하기

이제 검색 화면을 수정할 것이다. 정규 표현식 이라는 것이 있다. 이것은 string으로부터 무언가를 가져오는 것이다.

우리가 정규 표현식으로 하고 싶은건 handsome을 찾던 Handsome을 찾던 대소문자를 구별하지 않고 찾도록 하면서 내가 찾는 단어가 포함된 모든 걸 찾는 것이다.

 

 

export const search = async(req, res) => {

    const {query: { term: searchingBy }} = req;

    let videos = [];

    try{

        videos = await Video.find({title: {$regex: searchingBy, $options: "i"}});

    }catch(error){

        console.log(error);

    }

    res.render("search", {pageTitle: "Search", searchingBy, videos});

};

↑ videoController.js

정규표현식을 이용하기 위해 다음과 같이 작성했다.

option이 i라는 것은 insensitive(덜 민감한), 대소문자를 구별하지 않는 것이다.

let videos=[]로 한 이유는 try에서 비디오를 찾게 되면 그 찾은 비디오가 배열에 담겨서 표시될 것이고

아무것도 찾지 못하면 빈 배열로 render되게 하려고 한 것이다. 그래서 const를 쓰지 않은 것이다. 내가 찾은 videos로 재할당 할 것이기 때문에.

 

비디오를 찾지 못했다면 찾지 못했다는 메시지를 띄우도록 수정하기

extends layouts/main

include mixins/videoBlock

block content 

    .search__header

        h3 Searching for: #{searchingBy}

    .search__videos

        if videos.length === 0

            h5 No Videos Found

        each video in videos

            +videoBlock({

                title: video.title,

                views: video.views,

                videoFile: video.videoFile

            })

↑ search.pug

 

search화면에서 비디오 재생이 안되는 버그를 수정하자

extends layouts/main

include mixins/videoBlock

block content 

    .search__header

        h3 Searching for: #{searchingBy}

    .search__videos

        if videos.length === 0

            h5 No Videos Found

        each video in videos

            +videoBlock({

                title: video.title,

                views: video.views,

                videoFile: video.fileUrl,

                id: video.id

            })

↑ search.pug

db의 VideoSchema에 경로에 대한 key가 fileUrl로 되어있기 때문에

db에 경로가 fileUrl이라는 키로 접근해야 경로value를 가져올 수 있다.

 

videoDetail에서 댓글 수를 보여주는 코드를 수정하자

extends layouts/main

block content 

    .video__player 

        video(src=`/${video.fileUrl}`, width="30%", controls=true, autoplay=true)

    .video__info

        a(href=routes.editVideo(video.id)) Edit Video

        h5.video__title=video.title

        span.video__views=video.views

        p.video__description=video.description

    .video__comments

        if video.comments.length === 1

            span.video__comment-number 1 Comment 

        else 

            span.video__comment-number #{video.comments.length} Comments

↑ videoDetail.pug

 

그냥 단순히 1 comments가 되지 않게 하려고 저렇게 작성한 거 뿐이다.

728x90
반응형