Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Node check if objectid is valid

How can I check whether an ObjectID is valid using Node's driver

I tried :

var BSON = mongo.BSONPure; console.log("Validity: "  + BSON.ObjectID.isValid('ddsd')) 

But I keep getting an exception instead of a true or false. (The exception is just a 'throw e; // process.nextTick error, or 'error' event on first tick'

like image 351
Tarang Avatar asked Aug 16 '12 10:08

Tarang


People also ask

What is a valid ObjectId?

ObjectId values are 12 bytes in length, consisting of: a 4-byte timestamp value, representing the ObjectId's creation, measured in seconds since the Unix epoch. a 5-byte random value generated once per process. This random value is unique to the machine and process.

How does MongoDB compare ObjectId?

Mongoose uses the mongodb-native driver, which uses the custom ObjectID type. You can compare ObjectIDs with the . equals() method. With your example, results.

What is ObjectId in Nodejs?

ObjectID() id (string) – Can be a 24 byte hex string, 12 byte binary string or a Number.

What is MongoDB ObjectId?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.


2 Answers

This is a simple check - is not 100% foolproof

You can use this Regular Expression if you want to check for a string of 24 hex characters.

var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$")  checkForHexRegExp.test("i am a bad boy") // false checkForHexRegExp.test("5e63c3a5e4232e4cd0274ac2") // true 

Regex taken from github.com/mongodb/js-bson/.../objectid.ts


For a better check use:

var ObjectID = require("mongodb").ObjectID  ObjectID.isValid("i am a bad boy") // false ObjectID.isValid("5e63c3a5e4232e4cd0274ac2") // true 

isValid code github.com/mongodb/js-bson/.../objectid.ts

like image 120
Gianfranco P. Avatar answered Oct 16 '22 13:10

Gianfranco P.


isValid() is in the js-bson (objectid.ts) library, which is a dependency of node-mongodb-native.

For whoever finds this question, I don't recommend recreating this method as recommend in other answers. Instead, continue using node-mongodb-native like the original poster was using, the following example will access the isValid() method in js-bson.

var mongodb = require("mongodb"); var objectid = mongodb.BSONPure.ObjectID;  console.log(objectid.isValid('53fbf4615c3b9f41c381b6a3')); 

July 2018 update: The current way to do this is:

var mongodb = require("mongodb") console.log(mongodb.ObjectID.isValid(id)) 
like image 34
Eat at Joes Avatar answered Oct 16 '22 12:10

Eat at Joes