Mongodb 搜索功能未执行

时间:2021-03-11 01:18:31

标签: node.js mongodb express

我正在使用 react、nodejs 和 mongodb。我有一个搜索栏,它将发布请求发送到搜索功能,然后查询 mongodb 并返回结果。问题是函数永远不会被执行。

反应:

const getData = (searchValue) => {
const ourRequest = Axios.CancelToken.source();
async function fetchPost() {
  try {
    const response = await Axios.post(`/search`, {
      params: { searchValue },
      cancelToken: ourRequest.token,
    });
    if (response.data) {
      console.log(response.data);
    } else {
      dispatch({ type: 'notFound' });
    }
  } catch (e) {
    console.log('There was a problem or the request was cancelled.');
  }
}
fetchPost();
};

快递:

router.js

apiRouter.post('/search', postController.search);

postController.js

exports.search = function (req, res) {
  Post.search(req.body.searchTerm) 
    .then((posts) => {
      console.log('Hello..');
      res.json(posts);
    })
    .catch((e) => {
      res.json([]);
    });
};

Post.js:

Post.search = function (searchTerm) {
  return new Promise(async (resolve, reject) => {
    if (typeof searchTerm == 'string') {

       console.log('hello..', searchTerm) // nothing

       let posts = await Post.reusablePostQuery([
         { $match: { $text: { $search: searchTerm } } },
         { $sort: { score: { $meta: 'textScore' } } },
       ]);
      resolve(posts);
    } else {
      reject();
    }
  });
};

当我输入搜索时,我在开发控制台中得到一个空数组响应。

1 个答案:

答案 0 :(得分:2)

解决此类问题总是很困难,因为很多地方都可能存在问题。但我会指出一些突出的,希望它能引导您找到答案。

首先跳出来的是:req.body.searchTerm。您正在寻找 searchTerm 而您的 React 应用程序没有发送它。相反,您发送的是 searchValue,如 params: { searchValue } 中的转换为 params: { searchValue: searchValue }

所以你应该在你的 React 代码中改变两件事。

  1. 发送包含您的请求的正文。
  2. 使用正确的命名法,以便您的后端应用可以看到它。
const response = await Axios({
  method: 'post',
  url: '/search',
  data: {
    searchTerm: searchValue
  },
  cancelToken: ourRequest.token
})

理论上,这些更改应该可以解决您的问题。

相关问题