NodeJS 환경에서 MongoDB를 사용하여 검색 기능을 구현해보자.
사용하는 것
node.js, mongoDB, pug
form(method="get")
input(type="text" required name="keyword")
input(type="submit" value="Send")
검색 메서드는 post가 아닌 get을 사용한다.
input의 name은 적절하게 작명하자.
name을 빼먹으면 node.js에서 찾을 수 없으니 유의.
const search = async (req,res) =>{
const {keyword} = req.query;
let contents=[];
if(keyword){
//keyword가 있다면.
contents = await Contents.find({
//Contents = MongoDB의 Model이다.
title:{
$regex: new RegExp(`${keyword}`, "i"),
},
})
}
return res.send(contents)
}
regex을 지정하지 않으면 title의 단어를 하나도 틀리지 않고 검색해야 결과가 나온다. 여기서 i는 대문자, 소문자를 구별하지 않는다는 의미이다.
검색해서 나온 결과값은 자유롭게 page에서 활용하면 된다.
간단하게 MongoDB를 사용하여 검색 기능을 구현해보았다.