Javascript 我可以确定一个字符串是否是 MongoDB ObjectID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13850819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I determine if a string is a MongoDB ObjectID?
提问by Will
I am doing MongoDB lookups by converting a string to BSON. Is there a way for me to determine if the string I have is a valid ObjectID for Mongo before doing the conversion?
我正在通过将字符串转换为 BSON 来进行 MongoDB 查找。在进行转换之前,有没有办法让我确定我拥有的字符串是否是 Mongo 的有效 ObjectID?
Here is the coffeescript for my current findByID function. It works great, but I'd like to lookup by a different attribute if I determine the string is not an ID.
这是我当前 findByID 函数的咖啡脚本。它工作得很好,但如果我确定字符串不是 ID,我想通过不同的属性进行查找。
db.collection "pages", (err, collection) ->
collection.findOne
_id: new BSON.ObjectID(id)
, (err, item) ->
if item
res.send item
else
res.send 404
回答by Andy Macleod
I found that the mongoose ObjectId validator works to validate valid objectIds but I found a few cases where invalid ids were considered valid. (eg: any 12 characters long string)
我发现 mongoose ObjectId 验证器可以验证有效的 objectIds,但我发现在一些情况下无效的 ids 被认为是有效的。(例如:任何 12 个字符长的字符串)
var ObjectId = require('mongoose').Types.ObjectId;
ObjectId.isValid('microsoft123'); //true
ObjectId.isValid('timtomtamted'); //true
ObjectId.isValid('551137c2f9e1fac808a5f572'); //true
What has been working for me is casting a string to an objectId and then checking that the original string matches the string value of the objectId.
对我有用的是将字符串转换为 objectId,然后检查原始字符串是否与 objectId 的字符串值匹配。
new ObjectId('timtamtomted'); //616273656e6365576f726b73
new ObjectId('537eed02ed345b2e039652d2') //537eed02ed345b2e039652d2
This work because valid ids do not change when casted to an ObjectId but a string that gets a false valid will change when casted to an objectId.
之所以有效,是因为有效 id 在转换为 ObjectId 时不会更改,但在转换为 objectId 时,获得 false 有效值的字符串将更改。
回答by JohnnyHK
You can use a regular expression to test for that:
您可以使用正则表达式来测试:
CoffeeScript
咖啡脚本
if id.match /^[0-9a-fA-F]{24}$/
# it's an ObjectID
else
# nope
JavaScript
JavaScript
if (id.match(/^[0-9a-fA-F]{24}$/)) {
// it's an ObjectID
} else {
// nope
}
回答by cbaigorri
I have used the native node mongodb driver to do this in the past. The isValid method checks that the value is a valid BSON ObjectId. See the documentation here.
我过去曾使用本机节点 mongodb 驱动程序来执行此操作。isValid 方法检查该值是否是有效的 BSON ObjectId。请参阅此处的文档。
var ObjectID = require('mongodb').ObjectID;
console.log( ObjectID.isValid(12345) );
回答by nzjoel
Here is some code I have written based on @andy-macleod's answer.
这是我根据@andy-macleod 的回答编写的一些代码。
It can take either an int or string or ObjectId and returns a valid ObjectId if the passed value is valid or null if it is invalid:
它可以采用 int 或 string 或 ObjectId,如果传递的值有效,则返回有效的 ObjectId,如果无效,则返回 null:
var ObjectId= require('mongoose').Types.ObjectId;
function toObjectId(id) {
var stringId = id.toString().toLowerCase();
if (!ObjectId.isValid(stringId)) {
return null;
}
var result = new ObjectId(stringId);
if (result.toString() != stringId) {
return null;
}
return result;
}
回答by Sajag Porwal
mongoose.Types.ObjectId.isValid(string) always returns True if string contains 12 letters
如果字符串包含 12 个字母,则 mongoose.Types.ObjectId.isValid(string) 总是返回 True
let firstUserID = '5b360fdea392d731829ded18';
let secondUserID = 'aaaaaaaaaaaa';
console.log(mongoose.Types.ObjectId.isValid(firstUserID)); // true
console.log(mongoose.Types.ObjectId.isValid(secondUserID)); // true
let checkForValidMongoDbID = new RegExp("^[0-9a-fA-F]{24}$");
console.log(checkForValidMongoDbID.test(firstUserID)); // true
console.log(checkForValidMongoDbID.test(secondUserID)); // false
回答by AliAvci
Below is a function that both checks with the ObjectId isValidmethod and whether or not new ObjectId(id)returns the same value. The reason for isValidnot being enough alone is described very well by Andy Macleod in the chosen answer.
下面是一个函数,它既检查 ObjectIdisValid方法,又检查是否new ObjectId(id)返回相同的值。isValidAndy Macleod 在选择的答案中很好地描述了不够孤独的原因。
const ObjectId = require('mongoose').Types.ObjectId;
/**
* True if provided object ID valid
* @param {string} id
*/
function isObjectIdValid(id){
return ObjectId.isValid(id) && new ObjectId(id) === id;
}
回答by Daphoque
The only way i found is to create a new ObjectId with the value i want to check, if the input is equal to the output, the id is valid :
我发现的唯一方法是使用我要检查的值创建一个新的 ObjectId,如果输入等于输出,则 id 有效:
function validate(id) {
var valid = false;
try
{
if(id == new mongoose.Types.ObjectId(""+id))
valid = true;
}
catch(e)
{
valid = false;
}
return valid;
}
> validate(null)
false
> validate(20)
false
> validate("abcdef")
false
> validate("5ad72b594c897c7c38b2bf71")
true
回答by pkarc
If you have the hex string you can use this:
如果你有十六进制字符串,你可以使用这个:
ObjectId.isValid(ObjectId.createFromHexString(hexId));
回答by Vibhu Tewary
It took me a while to get a valid solution as the one proposed by @Andy Macleod of comparing objectId value with its own string was crashing the Express.js server on:
我花了一段时间才得到一个有效的解决方案,因为@Andy Macleod 提出的将 objectId 值与其自己的字符串进行比较的方法使 Express.js 服务器崩溃:
var view_task_id_temp=new mongodb.ObjectID("invalid_id_string"); //this crashed
I just used a simple try catch to solve this.
我只是使用了一个简单的 try catch 来解决这个问题。
var mongodb = require('mongodb');
var id_error=false;
try{
var x=new mongodb.ObjectID("57d9a8b310b45a383a74df93");
console.log("x="+JSON.stringify(x));
}catch(err){
console.log("error="+err);
id_error=true;
}
if(id_error==false){
// Do stuff here
}
回答by Om Sharma
For mongoose , Use isValid() function to check if objectId is valid or not
对于 mongoose ,使用 isValid() 函数检查 objectId 是否有效
Example :
例子 :
var ObjectId = mongoose.Types.ObjectId;
if(ObjectId.isValid(req.params.documentId)){
console.log('Object id is valid');
}else{
console.log('Invalid Object id');
}

