3

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
}
Community
  • 1
  • 1
Erik
  • 14,060
  • 49
  • 132
  • 218

2 Answers2

7

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');
  ...
});
robertklep
  • 198,204
  • 35
  • 394
  • 381
1

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);
}); 
Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159
  • Thanks for the response but how can I construct regexp for mongodb id checking? – Erik Oct 04 '13 at 17:31
  • What is the exact expression you're trying to target? You can always try your regular expressions to see if they capture what you need at http://regexpal.com/ – Traveling Tech Guy Oct 04 '13 at 17:34