【问题标题】:Mongodb search function not executingMongodb搜索功能未执行
【发布时间】:2021-03-11 12:43:43
【问题描述】:

我正在使用 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();
};

快递:

路由器.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();
    }
  });
};

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

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

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

    首先跳出来的是: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
    })
    

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

    【讨论】:

      猜你喜欢
      • 2021-02-19
      • 1970-01-01
      • 2018-01-18
      • 2010-09-12
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      相关资源
      最近更新 更多