그저 내가 되었고

🎯Node.js + mongoDB:: 게시판 검색 기능 본문

개발/DB

🎯Node.js + mongoDB:: 게시판 검색 기능

hyuunii 2022. 11. 22. 22:53

✓ 설명: 기본적으로 키워드 검색입니다. 그러므로 찾는 게시물의 제목이 ‘롤롤’일 경우 ‘롤’까지 입력해도 ‘롤롤’까지 전부 찾아집니다. 같은 방식으로 찾는 닉네임이 ‘안녕하세요’일 경우 ‘안녕’까지 입력해도 ‘안녕하세요’까지 전부 찾아집니다. 공백 무시하며, 영어 대소문자 무시하고 찾습니다.

 

✓ 로직: keyword를 params로 받아요. 3layered 기준 routes-posts-services 까지는 여타 API들과 같아요. repositories에서 find를 할 때 regular expression($regex)을 이용합니다.

++$regex? https://www.mongodb.com/docs/manual/reference/operator/query/regex/

 For data hosted on MongoDB Atlas, MongoDB offers a full-text search solution, MongoDB Atlas Search. If you frequently run case-insensitive regex queries (utilizing the i option), MongoDB recommends Atlas Search queries that use the $search aggregation pipeline stage.

 It provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support.

 

✓ 문제: DB 전체를 훑어서 결과를 긁는 방식이라 속도가 좀 걸립니다. 때문에, 검색하신 후 1초의 딜레이도 없이 바로 연이어 새로 검색을 하시면 결과가 나오지 않습니다(..) 트러블슈팅 필요. 

↳****hint) 연타를 방지하도록...? 왜냐면 원래 로딩이 걸리는건 맞거등.. 그니까 응답 시간동안 강제로 뭔가를 못하게 하는것도 방법. 기본적으로 더블클릭을 그냥 해버리는 사람들도 있으니까요~~

 

❤︎게시글 검색 by.제목 API:

➜URL: /posts/searchTitle/{keyword}

➜{keyword}: req.params

 

❤︎게시글 검색 by.닉네임 API:

➜URL: /posts/searchNickname/{keyword}

➜{keyword}: req.params


posts.router.js

router.get("/searchTitle/:keyword", postsController.searchTitle);  //게시글 검색 by 제목
router.get("/searchNickName/:keyword", postsController.searchNickName);  //게시글 검색 by 닉네임

 

 

controllers.posts.js

//게시글 검색 by 제목
    searchTitle = async (req, res, next) => {
        const {keyword} = req.params;
        const searchTitle = await this.postsService.searchTitle(keyword);
        res.status(200).json({data: searchTitle})
    }

//게시글 검색 by 닉네임
    searchNickName = async (req, res, next) => {
        const {keyword} = req.params;
        const searchNickName = await this.postsService.searchNickName(keyword);
        res.status(200).json({data: searchNickName})

 

 

services.posts.js

//게시글 검색 by 제목
    searchTitle = async(keyword) => {
        const searchTitle = await this.postsRepository.searchTitle(keyword)
        return searchTitle
    }

//게시글 검색 by 닉네임
    searchNickName = async(keyword) => {
        const searchNickName = await this.postsRepository.searchNickName(keyword)
        return searchNickName
    }

 

 

 

repositories.posts.js

 //게시글 검색 by 제목
    searchTitle = async(keyword) => {
        const searchTitle = await Posts.find( { title: { $regex: keyword, $options: "xi" }}).sort({ createdAt: "desc"});
            /*{$or: [
                    { title: { $regex: keyword, $options: "xi"}},  //“x” is to ignore the white space,
                    { nickName: {$regex: keyword, $options: "xi"}}  //“i” is to make it not case-sensitive
                ]}*/
        return searchTitle
    }

 //키워드(닉네임)로 게시글 검색
    searchNickName = async(keyword) => {
        const searchNickName = await Posts.find( { nickName: { $regex: keyword, $options: "xi" }}).sort({ createdAt: "desc"});
        return searchNickName
    }