0

I have a route /api/:id where :id has to be of type ObjectId. Because following is the query I am runnuing

const data = await Person.find({_id:req.params.id})

It works fine if :id is of type ObjectId but if user explicitly runs the api lets say /api/anything, then Mongoose throughs an error

CastError: Cast to ObjectId failed for value "anything" at path "_id"

So, I would like to check if req.params.id is of type ObjectId and perform further operations only if it is.

Thus code would look like

if(checkObjectId(req.params.id)) {
const data = await Person.find({_id:req.params.id})
}
Radical Edward
  • 2,824
  • 1
  • 10
  • 23
  • Maybe this will help? https://stackoverflow.com/questions/13850819/can-i-determine-if-a-string-is-a-mongodb-objectid – Ihor Vyspiansky Aug 28 '20 at 06:22
  • I'd combine the express param regex validation (e.g. `/api/:id(\d+)`) with a good regex that matches the ObjectId, e.g `[a-f\d]{24}` [here](https://stackoverflow.com/questions/20988446/regex-for-mongodb-objectid). That would mean `api/:id([a-f\d]{24})` should do here. – Wiktor Zychla Aug 28 '20 at 06:27

3 Answers3

2

Use the Mongoose functionality:

if(mongoose.isValidObjectId(req.params.id)) {
  const data = await Person.find({_id:req.params.id})
  ...
}

Mongoose.prototype.isValidObjectId()

Returns true if Mongoose can cast the given value to an ObjectId, or false otherwise.

mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true
mongoose.isValidObjectId('0123456789ab'); // true
mongoose.isValidObjectId(6); // false
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
2

you can use isValid method for validate object id

mongoose.Types.ObjectId.isValid('63d632828e944c3a08f15925')

0

Why if when you can use try ... catch

let data;
try {
    data = await Person.find({_id:req.params.id})
} catch(err) {
    console.log('Error retrieving data (Person):', err);
}
Aidil
  • 101
  • 1
  • 7