728x90
우리가 웹에서 가장 많이 사용하는 기능 중 하나는 검색기능이다.
리액트와 MongoDB로 검색 기능을 구현해보자 !
node.js로 이미지/정보 저장 후,
MongoDB에 저장 후...
[Client]
SearchPage.js 페이지 만들기
import React, { useState } from "react";
import { Input } from "antd";
const { Search } = Input;
function SearchPage() {
return (
<div>
<div>
<Search
placeholder="검색어를 입력하세요."
style={{
width: 200,
}}
/>
</div>
</div>
);
}
export default SearchPage;
AllData.js 만들기
import axios from "axios";
import React, { useEffect, useState } from "react";
import { Card, Row, Col } from "antd";
import ImageSlider from "./Sections/ImageSlider";
import { seasons, price } from "./Sections/Datas";
import DataCheckbox from "./Sections/DataCheckbox";
import DataRadioBox from "./Sections/DataRadioBox";
import SearchPage from "./Sections/SearchPage";
const { Meta } = Card;
function AllData() {
return (
<div style={{ width: "100%", margin: "0" }}>
<br />
<br />
<br />
<br />
<h2 style={{ textAlign: "center" }}>DB에 저장한 거 확인하기</h2>
<Row>
{/* checkBox */}
<Col lg={10} xs={20} style={{ position: "relative", left: "8.5%" }}>
<DataCheckbox
list={seasons}
boxFilters={(filters) => boxFilters(filters, "seasons")}
/>
</Col>
{/* radioBox */}
<Col lg={10} xs={20} style={{ position: "relative", left: "2%" }}>
{/* RadioBox */}
<DataRadioBox
list={price}
boxFilters={(filters) => boxFilters(filters, "price")}
/>
</Col>
</Row>
{/* search */}
<div
style={{
display: "flex",
justifyContent: "flex-end",
margin: "1rem auto",
width: "65%",
}}
>
<DataSearch /> //추가
</div>
{/* card */}
<div style={{ width: "85%", margin: "1rem auto" }}>
<Row gutter={[20, 20]}>{renderCard}</Row>
</div>
{LimitImage >= End && (
<div style={{ display: "flex", justifyContent: "center" }}>
<button style={{}} onClick={showMoreData}>
더 보기
</button>
</div>
)}
</div>
);
}
export default AllData;
search 작동 기능 만들기
SearchPage.js
import React, { useState } from "react";
import { Input } from "antd";
const { Search } = Input;
function SearchPage(props) {
const [SearchItem, setSearchItem] = useState("");
const searchHandler = (event) => {
setSearchItem(event.currentTarget.value);
props.refreshFunction(event.currentTarget.value);
};
return (
<div>
<div>
<Search
placeholder="검색어를 입력해주세요."
style={{
width: 200,
}}
value={SearchItem}
onChange={searchHandler}
/>
</div>
</div>
);
}
export default SearchPage;
AllData.js
import axios from "axios";
import React, { useEffect, useState } from "react";
import { Card, Row, Col } from "antd";
import ImageSlider from "./Sections/ImageSlider";
import { seasons, price } from "./Sections/Datas";
import DataCheckbox from "./Sections/DataCheckbox";
import DataRadioBox from "./Sections/DataRadioBox";
import SearchPage from "./Sections/SearchPage";
const { Meta } = Card;
function AllData() {
const [SearchItem, setSearchItem] = useState("");
useEffect(() => {
let body = {
start: Start,
end: End,
};
commonAxios(body);
}, []);
//더 보기에 두 번 들어가기 때문에 따로 분리
const commonAxios = (body) => {
//post에 info값 넣을 것
axios.post("/api/data/list", body).then((response) => {
if (response.data.success) {
// console.log(response.data);
if (body.showMore) {
setDatas([...Datas, ...response.data.dataInfo]);
} else {
setDatas(response.data.dataInfo);
}
setLimitImage(response.data.limitImage);
} else {
alert("상품을 가져오는데 실패했습니다.");
}
});
};
const updateSearchItem = (newSearchItem) => {
let body = {
start: 0,
end: End,
filters: Filters,
searchItem: newSearchItem,
};
setStart(0);
setSearchItem(newSearchItem);
commonAxios(body);
};
return (
<div style={{ width: "100%", margin: "0" }}>
<br />
<br />
<br />
<br />
<h2 style={{ textAlign: "center" }}>DB에 저장한 거 확인하기</h2>
<Row>
{/* checkBox */}
<Col lg={10} xs={20} style={{ position: "relative", left: "8.5%" }}>
<DataCheckbox
list={seasons}
boxFilters={(filters) => boxFilters(filters, "seasons")}
/>
</Col>
{/* radioBox */}
<Col lg={10} xs={20} style={{ position: "relative", left: "2%" }}>
{/* RadioBox */}
<DataRadioBox
list={price}
boxFilters={(filters) => boxFilters(filters, "price")}
/>
</Col>
</Row>
{/* search */}
<div
style={{
display: "flex",
justifyContent: "flex-end",
margin: "1rem auto",
width: "65%",
}}
>
<DataSearch refreshFunction={updateSearchItem} /> //추가
</div>
{/* card */}
<div style={{ width: "85%", margin: "1rem auto" }}>
<Row gutter={[20, 20]}>{renderCard}</Row>
</div>
{LimitImage >= End && (
<div style={{ display: "flex", justifyContent: "center" }}>
<button style={{}} onClick={showMoreData}>
더 보기
</button>
</div>
)}
</div>
);
}
export default AllData;
[Server]
Data.js(스키마 포함된 값)
const mongoose = require("mongoose");
const dataSchema = sql.Schema(
{
title: {
type: String,
},
description: {
type: String,
maxlength: 50,
},
images: {
type: Array,
default: [],
},
seasons: {
type: Number,
default: 1,
},
price: {
type: Number,
default: 0,
},
//시간 자동 업데이트
},
{ timestamps: true }
);
dataSchema.index(
{
title: "text",
description: "text",
},
{
weight: {
title: 5,
description: 1,
},
}
);
const Data = mongoose.model("Data", dataSchema);
module.exports = { Data };
data.js(routes)
router.post("/list", (req, res) => {
let item = req.body.searchItem;
if (item) { //검색기능이 포함된 값
Data.find(findData)
.find({ $text: { $search: item } })
.populate("title")
.skip(start)
.limit(end)
.exec((err, dataInfo) => {
if (err) return res.status(400).json({ success: false, err });
return res
.status(200)
.json({ success: true, dataInfo, limitImage: dataInfo.length });
});
} else { //검색기능이 포함되지 않은 값
Data.find(findData)
.populate("title")
.skip(start)
.limit(end)
.exec((err, dataInfo) => {
if (err) return res.status(400).json({ success: false, err });
return res
.status(200)
.json({ success: true, dataInfo, limitImage: dataInfo.length });
});
}
});
더보기

$text : MongoDB에 있는 검색기능이다.

728x90
'JavaScript > React' 카테고리의 다른 글
[React] 리액트 좋아요 기능 구현하기 (0) | 2023.03.23 |
---|---|
[React] React.Fragment 사용하기 (0) | 2023.03.21 |
[React] Redux 상태 관리 라이브러리 (0) | 2023.03.17 |
[React] Link 페이지 이동 시 스크롤 맨 위로 오게 하기 (0) | 2023.03.15 |
[React] 리액트 Swiper 사용하기 (리액트 터치 슬라이드) (0) | 2023.03.11 |
댓글