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})
}
2
  • Maybe this will help? stackoverflow.com/questions/13850819/… Commented Aug 28, 2020 at 6: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. That would mean api/:id([a-f\d]{24}) should do here. Commented Aug 28, 2020 at 6:27

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

2

you can use isValid method for validate object id

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

Comments

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

1 Comment

Thats not the way of checking :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.