我尝试了类似这些字符串的东西,它返回true意外! !
- mohamma22144
- mohamma22145
这个功能足够可靠吗?
mongoose.Types.ObjectId.isValid('mohamma22145')
isValid()
和isValidObjectId()
返回true,即使字符串不是ObjectId。根据docs
如果Mongoose可以将给定值强制转换为ObjectId则返回true,否则返回false。
如果你想检查是否是一个真正的ObjectId,你可以使用这个RegEx:/^[a-fd]{24}$/i
例子:
var regex = new RegExp(/^[a-fd]{24}$/i);
const ids = ['1', 'mohamma22145', '5a934e000102030405000000', 'FFFFFFFFFFFFFFFFFFFFFFFF']
ids.forEach(id => console.log(`${id} is an ObjectId: ${regex.test(id)}`))
ObjectId.isValid(id)即使对于长度为12的无效字符串也返回true。例如:
String ID | ObjectId.isValid(id) | Expected Validation
---------------------------------------------------------------------------
594ced02ed345b2b049222c5 | true | true
dania | false | false
toptoptoptop | true(but isnt) | false
daniandanian | true(but isnt) | false
---------------------------------------------------------------------------
为了防止这种情况,可以在默认验证器之后添加另一个检查,它将根据条件返回true或false,(从string创建的新ObjectId)转换为string === string即(String)(new ObjectId(id)) === id
可以创建如下函数来检查字符串是否为有效的ObjectId:
// Requiring ObjectId from mongoose npm package
const ObjectId = require('mongoose').Types.ObjectId;
// Validator function
function isValidObjectId(id){
if(ObjectId.isValid(id)){
if((String)(new ObjectId(id)) === id)
return true;
return false;
}
return false;
}
// Loading testcases into array
const testStrings = [ "594ced02ed345b2b049222c5","geeks",
"toptoptoptop","geeksfogeeks"];
// Validating each test case
for(const testcase of testStrings){
if(isValidObjectId(testcase))
console.log(testcase + " is a valid MongodbID");
else
console.log(testcase + " is not a valid MongodbID");
}
结果是:
String ID | ObjectId.isValid(id) | Expected Validation
---------------------------------------------------------------------------
594ced02ed345b2b049222c5 | true | true
dania | false | false
toptoptoptop | false | false
daniandanian | false | false