2

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?

Manish Shrestha
  • 411
  • 8
  • 12
Cupkek05
  • 458
  • 1
  • 6
  • 22

2 Answers2

8

With 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.

Cupkek05
  • 458
  • 1
  • 6
  • 22
1

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.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;
}

and then create an ObjectId from the Hexadecimal string the way it is suggested from the mongoDB Documentation (https://docs.mongodb.com/manual/reference/method/ObjectId/)

Specify a Hexadecimal string

To generate a new ObjectId using ObjectId() with a unique hexadecimal string:

y = ObjectId("507f191e810c19729de860ea")
Anastasios Selmani
  • 3,579
  • 3
  • 32
  • 48
  • ObjectID are created by themselves when I am creating a user. Actually, I am checking if the user is registered before inserting an object. my URL need the ObjectID of the user to insert an object. I would like to check if the ObjectID passed in the URL is a correct ObjectID or not. I don't want to create ObjectID by myself with your Hex method :) – Cupkek05 Sep 26 '17 at 09:32
  • Maybe this post is what you need? https://stackoverflow.com/questions/13850819/can-i-determine-if-a-string-is-a-mongodb-objectid – Anastasios Selmani Sep 26 '17 at 10:59
  • Ye maybe but it is possible to check that just with a regex ? It will have to match if it's a string of 24 hex characters or a single string of 12 bytes. Those validations must be possible with regex I guess... – Cupkek05 Sep 26 '17 at 12:16