首页 > 解决方案 > 反应 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));

});

标签: reactjsmongodbsearch

解决方案


推荐阅读