Question

This question inspired by this post but in my case I need to filter MongoId. Is it possible to make filtering easily that the below because I need use it in each route?

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

Solution

You're almost there, just don't add the ^ and $ anchors. And the uppercase A-F range isn't even necessary since Express seems to match case-insensitive:

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

OTHER TIPS

According to the Express API documentation, yes, you can use a regular expression as a path:

Regular expressions may also be used, and can be useful if you have very specific restraints.

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);
}); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top