[英]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.我有一条路线
/api/:id
where:id 必须是 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它工作正常如果:id 是类型
ObjectId
但如果用户显式运行 api 让我们说/api/anything
,然后 Mongoose 通过错误
CastError: Cast to ObjectId failed for value "anything" at path "_id"
CastError:转换为 ObjectId 失败,因为路径“_id”中的值“anything”
So, I would like to check if req.params.id
is of type ObjectId
and perform further operations only if it is.因此,我想检查
req.params.id
是否属于ObjectId
类型,只有在是的情况下才执行进一步的操作。
Thus code would look like因此代码看起来像
if(checkObjectId(req.params.id)) {
const data = await Person.find({_id:req.params.id})
}
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 可以将给定的值转换为 ObjectId,则返回 true,否则返回 false。
mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true mongoose.isValidObjectId('0123456789ab'); // true mongoose.isValidObjectId(6); // false
you can use isValid method for validate object id您可以使用 isValid 方法来验证 object id
mongoose.Types.ObjectId.isValid('63d632828e944c3a08f15925')
mongoose.Types.ObjectId.isValid('63d632828e944c3a08f15925')
Why if
when you can use try ... catch
为什么
if
你可以使用try ... catch
let data;
try {
data = await Person.find({_id:req.params.id})
} catch(err) {
console.log('Error retrieving data (Person):', err);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.