【问题标题】:Partial string matching - GET request API - Mongoose, Express, Node部分字符串匹配 - GET 请求 API - Mongoose、Express、Node
【发布时间】:2020-10-28 05:34:47
【问题描述】:

我有一个 GET 请求,当我输入餐厅时成功返回餐厅。它使用排序规则和索引,因此可以找到大小写,没问题。

问题是我必须输入准确的餐厅名称,否则 Postman 中的 GET 请求会失败。

例如要查找名为Riverside Shard Inn 的餐厅,只有在查询中输入Riverside Shard Inn 时,我的GET 请求才会找到它。如果我输入 Riverside ShardShard Inn 这将失败。

所以我想我需要在后端进行部分字符串匹配。不知道该怎么做。

这是我的 GET 请求代码:

    // Route to return a single restaurant using a collection that has collation//
    app.route("/restaurants/:restaurantName")
    
    .get(function(req, res){
      Restaurant.find({BusinessName: req.params.restaurantName}, function(err, foundRestaurant){
        if (foundRestaurant) {
          res.send(foundRestaurant)
        } else {
          res.send("No restaurants matching that title was found.");
        }
      });
    });

【问题讨论】:

    标签: node.js express mongoose get mongodb-query


    【解决方案1】:

    您可以使用正则表达式来搜索部分匹配。 RegExp 对象用于将文本与模式匹配。因此,您可以将您的部分字符串视为字符串中需要匹配的模式。

    所以,你可以这样做 -

    .get(function(req, res){
      let partialToMatch= new RegExp(req.params.restaurantName,'i'); 
      Restaurant.find({BusinessName: partialToMatch}, function(err, foundRestaurant){
        if (foundRestaurant) {
          res.send(foundRestaurant)
        } else {
          res.send("No restaurants matching that title was found.");
        }
      });
    });
    

    如果 BusinessName 的任何子字符串与 req.params.restaurantName 匹配,上述代码将返回匹配项。这里i修饰符用于执行不区分大小写的匹配。

    您也可以参考$regex 来实现相同的功能。我不熟悉它,并且在我与 mongoose 一起使用 nodejs 时,我个人使用过 RegExp。

    希望这会有所帮助!

    【讨论】:

    • @vernfunnell 很高兴为您提供帮助!如果有帮助,您可以接受我的回答
    猜你喜欢
    • 2022-11-07
    • 2015-07-05
    • 2012-06-15
    • 1970-01-01
    • 2015-12-16
    • 2014-09-15
    • 2019-10-18
    • 2017-07-02
    • 1970-01-01
    相关资源
    最近更新 更多