GET请求始终默认为/?:/ i-如何使其“未定义”? -关于这个主题的第二个问题

问题描述

在这里,我得到了一些很大的帮助,可以修复我的GET请求始终认为/(?:)/ i。我现在可以将GET设置为undefined。

但是,这仅在我的数据库搜索一个字段“ BusinessName”时有效。 我的问题是,我如何搜索多个字段,所以要搜索“ BusinessName”和“ Address”。 这是它的代码,仅在一个字段中搜索即可工作:

app.get("/widget",function(req,res) {


  // This  returns just one restaurant and doesnt do partial string matching
  /* let test = req.query.search */

  // This returns up to 200 results that partially match the search term
  /*  let test = new RegExp (req.query.search,'i'); */

  // This sets the query to undefined,to start with
    const test = (req.query.search)
    ? new RegExp(req.query.search,'i')
    : undefined

  Restaurant.find({
    BusinessName: test
  },null,{
    limit: 200
  },function(err,foundRestaurant) {
    console.log(test);

    if (foundRestaurant) {

      /* res.send(foundRestaurant) */
      res.render("widget",{
        foundRestaurant
      })
    } else {
      res.render("widget","No restaurants matching that title was found.");
    }
  });
});

这是我尝试使用“ AddressLine3”和“ AddressLine4”字段使其正常工作的尝试:

app.get("/town_widget",res) {

  const test3 = (req.query.search)
  ? new RegExp(req.query.search,'i')
  : undefined

  const test4 = (req.query.search)
  ? new RegExp(req.query.search,'i')
  : undefined

  Restaurant.find({
$or:[{
      AddressLine3: test3
    },{
      AddressLine4: test4
    }]},{
      limit: 2
    },foundTown) {
      if (foundTown) {
        console.log(foundTown);
        res.render("town_widget",{
          foundTown
        })
      } else {
        res.render("town_widget","No town or city matching that input was found/no restaurants found in the town specified.");
      }
    });

});

解决方法

O.Jones感谢您的帮助。我实际上发现我在做什么错,AddressLine4在我的数据库中不存在,因此在我的mongo请求中包含它会导致错误-我确实有AddressLine4,但现在我没有。现在使用OR运算符,一切都很好,欢呼