0

Im trying to create an ObjectId with mongoose in my node.js app from the parameters in the route.

If I got this route:

/product/:id

and I try to create my ObjectId for quering the product collection I use this

var o_id = moongose.Types.ObjectId(req.params.id);

But if the :id part of the route is NOT an ObjectId string, just some random text I get an error:

"Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"

How do I catch this error? I have tried to surround o_id = moongose.Types.ObjectId(req.params.id) with try{}catch(error) {} but I get nothing in the catch expression.

Goran
  • 1,002
  • 3
  • 14
  • 29
  • Possible duplicate of http://stackoverflow.com/questions/14940660/whats-mongoose-error-cast-to-objectid-failed-for-value-xxx-at-path-id – JohnnyHK Jul 07 '14 at 13:47

1 Answers1

1

The best way is to use a regex to test your expression:

if(/[a-f0-9]{24}/.test(req.params.id)) {
   var o_id = moongose.Types.ObjectId(req.params.id);
}
Vinz243
  • 9,654
  • 10
  • 42
  • 86