reactjs - 反应 mongodb 将文本传递到后端以进行搜索功能
问题描述
我正在为带有反应 mongodb、node.js 的项目开发搜索功能。我尝试更喜欢来自 mongodb 的文本搜索。我不知道我是否正确地将文本传递到后端进行查询,它不起作用。这是我的代码:
前端:
// getting search term
const searchTerm = "EarlyBird"
// pass the search term to the router to search the post
useEffect(() =>{
axios.get(`http://localhost:3001/searchPosts/${searchTerm}`)
.then(res => {
setPosts(res.data);
})
.catch(err => {
console.log(err);
})
});
后端:
// configure the router for search posts
router.route("/searchPosts/:searchTerm").get((req, res) => {
// create text index for text search
Post.createIndexe( { title: "text" } );
// set the search term
const query = {$text: {$search: req.query.searchTerm, $language: 'en'}};
// find the posts
Post.find(query)
.then(notes => res.json(notes))
.catch(err => res.status(400).json("Error: "+ err));
});
解决方案
推荐阅读
- php - 故意不捕捉异常
- buffer - 在 GeoDMS 中,我试图缓冲一个多边形,但出现错误
- reactjs - 如何通过导出在非索引文件中渲染 react-data-grid?
- javascript - 如何将秒转换为分钟和秒?
- python - 正则表达式分组直到空格
- java - selenium webdriver中的警报后如何处理基于窗口的弹出窗口?
- python - 需要帮助改进代码以运行 for 循环以汇总 csv 文件中的经济变量?
- r - 根据来自另一个数据帧的值替换数据帧中的行元素
- c# - 如何通过 C# 在 MS Visio 中获取形状对象的颜色
- flutter - 如何使用 1 NavigationBarItem 实现 BottomNavigationBar