MongoDB Node check if objectid is valid


Question

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'

1
47
8/16/2012 10:26:47 AM

Accepted Answer

Not sure where the isValid() function comes from but it's not in node-mongodb-native.

You could 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}$");

Taken from github.com/mongodb/js-bson/.../objectid.js

70
12/13/2018 12:04:51 PM

isValid() is in the js-bson 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"),
    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))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon