我怎么能检查它是否是一个12字节的String对象,MongoDB中的ObjectID?

我想检查一个正确的ObjectID来继续我的代码。 我在NodeJS上,我不想得到这个错误:

错误:传入的参数必须是12个字节的单个string或24个hex字符的string

其实我有这些testing:

if (!user.id || !user.id.match("/^[0-9a-fA-f]{24}$") || !typeof(user.id) === 'string') { console.log("user id is required !") return callback("user id is required !") } 

对于24个hex字符的string,我得到这个正则expression式:

 !user.id.match("/^[0-9a-fA-f]{24}$") 

我正在检查它是否是一个12字节的string:

 !typeof(user.id) === 'string' 

我应该如何为12个字节添加validation?

有什么想法吗?

从我所看到的你可以通过作为一个Id你想要的任何string。 你应该先把它变成hexstring( http://forums.devshed.com/javascript-development-115/convert-string-hex-674138.html

 function toHex(str) { var hex = ''; for(var i=0;i<str.length;i++) { hex += ''+str.charCodeAt(i).toString(16); } return hex; } 

然后从mongoDB文档( https://docs.mongodb.com/manual/reference/method/ObjectId/ )中build议从hexstring中创buildObjectId,

指定一个hexstring

使用带唯一hexstring的ObjectId()生成新的ObjectId:

 y = ObjectId("507f191e810c19729de860ea") 

使用NodeJS,如果你正在使用:

 const objectID = require('mongodb').objectID 

你可以简单地testing你的ObjectID:

 ObjectID.isValid(yourobjectid) 

如果有效则返回true,否则返回false。