MongDB 에 접근해 값을 가져올것이다.
1. 특정 string 이 포함되어 있는 조건
2. 여러개의 특정 stiring 들 이 하나라도 포함되어 있다면 가져오는 조건
3. 특정 string 이 전부 포함되어야만 가져오는 조건
MongDB 의 매뉴얼을 보자
https://www.mongodb.com/docs/manual/reference/operator/query/regex/
나도 사용해본다.
1. String 이 포함되어 있다면 만족 ( $regex )
$regex : "string" // 혹은
$regex : /string/
DB의 값에 "string" 이라는 글자가 들어있다면 만족하므로
{ data : "is include string"}
{ data : "is not include sting"}
결과적으로
{ data : "is include string"}
해당 값이 가져와질것이다.
2. 하나라도 만족 ( $or ) 혹은 전부 만족 ( $and )
$and : [
data:{"hi"}
data:{"bye"}
]
-------------------------------------
$or : [
data:{"hi"}
data:{"bye"}
]
조건이 조금 이상하긴 하지만,
data:{"hi"} 이면서 data:{"bye"} 를 전부 만족 → ( $and )
data:{"hi"} 혹은 data:{"bye"} 둘중 하나라도 만족 → ( $or)
3. 따라서, 최종적으로 $regex 와 $or , $and 조건을 이용하여, MongoDB 의 값을 가져와보자.
req.body.personality 는 배열이다.
req.body.personality 안에는 [ "x", "y", "z"] 가 들어있다.
MongoDB 에서 Find 를 할때, "x" 혹은 "y" 혹은 "z" 가 하나라도 문자열에 포함되어 있다면 그 값을 가져올것이다.
< api / test.ts >
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const dbName = "...";
const collectionName = "...";
const result = await client
.db(dbName)
.collection(collectionName)
.find({
$or: [ // $or 을 통해, 하나의 조건만 만족하더라도 선택
{ personality: { $regex: req.body.personality[0] } }, // $regex 를 통해, 해당값이 포함되어있다면 선택
{ personality: { $regex: req.body.personality[1] } },
],
size: req.body.size }).toArray();
};
조금더 세련되게 만들어보자.
.find({
$or: req.body.personality.map((item: string) => ({
personality: { $regex: item },
})),
size: req.body.size,
})
반복문을 통해, 깔끔하게 만들어보았다.
'메인-프로젝트 > Next.js - 심리검사와 강아지 프로젝트' 카테고리의 다른 글
10. [오류] 배포와 Oauth (0) | 2023.02.09 |
---|---|
9. 이번 프로젝트의 전체적인 로직에 관하여 (0) | 2023.02.06 |
7. useCallback 을 이용한 fetch ( 비동기함수 ) 사용하기, useEffect 초기 렌더시 내부함수 사용 금지하기 (0) | 2023.02.03 |
6. SASS, @for 과 @if 를 활용한, 스타일링 지정 (0) | 2023.02.03 |
5. POST 를 이용한 데이터 가져오기, 로컬스토리지에 저장하기 (0) | 2023.02.03 |
댓글