【问题标题】:GET request always defaults to /(?:)/i - how can i make it 'undefined'? - Second question on this topicGET 请求始终默认为 /(?:)/i - 我怎样才能使其“未定义”? - 关于这个话题的第二个问题
【发布时间】:2020-09-26 10:50:04
【问题描述】:

我在这里得到了一些很大的帮助来修复我的 GET 请求总是默认为 /(?:)/i。我现在可以将我的 GET 设置为未定义。

但是,这仅在我的数据库中搜索一个字段“企业名称”时有效。 我的问题是,我如何搜索多个字段,所以“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", function(req, 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
    }]},
    null, {
      limit: 2
    },

    function(err, 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.");
      }
    });

});

【问题讨论】:

  • 你是 MongoDb 吗?如果是这样,请将该标签添加到您的问题中,然后查找 $and 运算符。
  • 嗨 O.Jones,我数据中的城镇有时位于 AddressLine3 中,有时位于 AddressLine4 中。所以我使用了 Or 运算符。我应该使用 And 运算符吗?如果我使用 Or 运算符,它会忘记查询是未定义的,并且总是在我加载页面时进行搜索,然后再输入搜索查询

标签: node.js mongodb express get xregexp


【解决方案1】:

O.Jones 感谢您的帮助。我实际上发现我做错了什么,我的数据库中不存在 AddressLine4 ,因此将其包含在我的 mongo 请求中会导致错误 - 我曾经有过 AddressLine4 但现在我没有。现在一切都与 OR 运算符配合得很好,干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多