【问题标题】:Express.js - Filter a mongodb id in the URLExpress.js - 在 URL 中过滤一个 mongodb id
【发布时间】:2017-02-10 08:38:55
【问题描述】:

这个问题的灵感来自this post,但就我而言,我需要过滤 MongoId。是否可以轻松地进行以下过滤,因为我需要在每条路线中使用它?

app.post('/:mongoId(^[0-9a-fA-F]{24}$)', function(req, res){
   // Send query based on mongoId
}

【问题讨论】:

    标签: node.js mongodb filter express node-mongodb-native


    【解决方案1】:

    你快到了,只是不要添加 ^$ 锚点。而且大写的A-F 范围甚至不是必需的,因为 Express 似乎匹配不区分大小写:

    app.post('/:mongoId([0-9a-f]{24})', function(req, res){
      var id = req.param('mongoId');
      ...
    });
    

    【讨论】:

      【解决方案2】:

      根据Express API documentation,可以,可以用正则表达式作为路径:

      也可以使用正则表达式,如果你有 非常具体的限制。

      app.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function(req, res){
        var from = req.params[0];
        var to = req.params[1] || 'HEAD';
        res.send('commit range ' + from + '..' + to);
      }); 
      

      【讨论】:

      • 感谢您的回复,但是我该如何构造用于 mongodb id 检查的正则表达式?
      • 您要针对的确切表达方式是什么?您可以随时在regexpal.com 尝试您的正则表达式,看看它们是否捕获了您需要的内容
      猜你喜欢
      • 2014-09-22
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 2021-07-11
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      相关资源
      最近更新 更多