I'd like to check for a correct ObjectID to continue my code. I'am on NodeJS and I don't want to get the error:
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
Actually I got those tests:
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 !")
}
For string of 24 hex characters I got this regex :
!user.id.match("/^[0-9a-fA-f]{24}$")
And I am searching for check if it is a string of 12 bytes :
!typeof(user.id) === 'string'
How should I add the verification for the 12 bytes?
Any idea please?
I'd like to check for a correct ObjectID to continue my code. I'am on NodeJS and I don't want to get the error:
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
Actually I got those tests:
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 !")
}
For string of 24 hex characters I got this regex :
!user.id.match("/^[0-9a-fA-f]{24}$")
And I am searching for check if it is a string of 12 bytes :
!typeof(user.id) === 'string'
How should I add the verification for the 12 bytes?
Any idea please?
Share Improve this question edited Mar 11, 2019 at 12:41 Manish Shrestha 4408 silver badges15 bronze badges asked Sep 26, 2017 at 9:02 Cupkek05Cupkek05 4681 gold badge6 silver badges23 bronze badges 6- Check out github./Automattic/mongoose/issues/1959 – chridam Commented Sep 26, 2017 at 9:07
- Are you really asking us "how do you check a string is 12 characters long"? – Tom Lord Commented Sep 26, 2017 at 9:09
- I am asking for both in a same test @TomLord – Cupkek05 Commented Sep 26, 2017 at 9:10
-
2
@Cupkek05
^(.{12}|[0-9a-fA-f]{24})$
??... – Tom Lord Commented Sep 26, 2017 at 9:12 - @TomLord, thanks, it works, sorry I am new with regex... It is not so simple to understand :/ – Cupkek05 Commented Sep 26, 2017 at 9:15
2 Answers
Reset to default 8With NodeJS if you are using :
const objectID = require('mongodb').objectID
You could simply test your ObjectID like that :
ObjectID.isValid(yourobjectid)
It will return true if it is valid and false if it is not.
From what I see you can pass as an Id any string you want. You should probably turn it into Hexadecimal string first (http://forums.devshed./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;
}
and then create an ObjectId from the Hexadecimal string the way it is suggested from the mongoDB Documentation (https://docs.mongodb./manual/reference/method/ObjectId/)
Specify a Hexadecimal string
To generate a new ObjectId using ObjectId() with a unique hexadecimal string:
y = ObjectId("507f191e810c19729de860ea")