티스토리 뷰

📌 2020 07 24

  • 전체 상품 중에서 특정 키워드가 title에 들어간 상품 검색 기능 구현
  1. 몽고 db에서는 searching 기능을 제공해주는데, 먼저 검색의 대상이 되고자 하는 컬렉션 필드를 text index로 등록해줘야 한다. 아래와 같이 등록해주면 된다.
Schema.index({필드명: 'text'});
const mongoose =require('mongoose');
const Schema = mongoose.Schema;

const ProductSchema = new Schema({
    title:{
        type:String,
        required:true
    },
    price:{
        type:Number,
        required:true
    },
    imageUrl:{
        type:String,
        required:true
    },
    description:{
        type:String,
        required:true
    },
    userId:{
        type:Schema.Types.ObjectId,
        required:true
    }
});
ProductSchema.index({title: 'text'}); // text index로 등록 
module.exports=mongoose.model('Product',ProductSchema);
  1. 이제 사용자가 검색한 키워드를 서버에 받아오기 위해 form 을 만들어주고, method는 GET으로 해주어 해당 키워드를 쿼리로 담아온다.
 <form action="/search" method="GET">
    <label>title search</label>
    <input class ="searchBox" type="text" name="searchWord">
    <button class="btn" type="submit">search</button>
</form>
  1. searchWord 쿼리에 담아온 데이터를 이용해서 Product 스키마에게 search 쿼리를 적용하여 특정 상품만 받아오도록 하자.
Product.find({ $text : {$search: searchWord}})

이렇게 입력해주면 해당하는 product만 가져올 수 있다.

  • 추가 : 나는 searching Result 페이지에도 pagination을 구현했기 때문에 부가적인 요소있다.
    • searchWord쿼리와 함께 page쿼리에는 page number를 담아왔다.
    • 여기서 주의 할점은 아래 예시처럼 쿼리를 두개이상 보낼 때는 각 쿼리들을 '& '으로 연결시키고, 뒤에오는 쿼리문에는 ? 을 붙여선 안된다.
http://localhost:3000/search?searchWord=text&page=1
exports.getSearch=(req,res,next)=>{ // 상품 찾기
    const searchWord = req.query.searchWord; // 쿼리에 담아온 
    console.log(searchWord);
    let pageNum=1;
    if(req.query.page){  pageNum=+req.query.page; } // 페이지 번호 담아오기 
    console.log(req.query.page);
    let totalItems; 
    Product.find({ $text : {$search: searchWord}}).countDocuments() // 전체 아이템 수 
    .then(itemsNum=>{ 
        totalItems=itemsNum;
        return Product.find({ $text : {$search: searchWord}}) 
        .skip((pageNum-1)*POST_PER_PAGE) // 앞 페이지 product skip  
        .limit(POST_PER_PAGE) // 현재 페이지에 와야할 product 수 
    })
    .then(products=>{
        res.render('shop/searchingResult', {
            pageTitle: 'searching result',
            path:'/search?searchWord='+searchWord,
            prods: products,
            currentPage:pageNum, // 현재 페이지 
            hasNextPage: POST_PER_PAGE*pageNum < totalItems, // 다음 페이지가 있는가? 
            hasPreviousPage: pageNum>=2, // 이전 페이지가 있는가? 
            nextPage: pageNum+1, // 다음페이지 
            previousPage:pageNum-1, //이전페이지 
            lastPage: Math.ceil(totalItems/POST_PER_PAGE) //마지막 페이지 
        })
        })
    .catch(err =>console.log(err));
}

 

 

 

몽고 db의 serach 기능에 대한 더 많은 정보는 docs.mongodb.com/manual/text-search/ 에 있다!

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함