Ranjeet Eppakayala
Ranjeet Eppakayala

Reputation: 3028

How to check if string is of type ObjectId in Node.js

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

Upvotes: 0

Views: 4632

Answers (3)

Amir Mohammad Beheshti
Amir Mohammad Beheshti

Reputation: 154

you can use isValid method for validate object id

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

Upvotes: 2

Aidil
Aidil

Reputation: 101

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

Upvotes: 0

Ionică Bizău
Ionică Bizău

Reputation: 113365

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

Upvotes: 2

Related Questions