Search code examples
node.jsmongodbfilterexpressnode-mongodb-native

Express.js - Filter a mongodb id in the URL


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
}

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');
      ...
    });