MongoDB Node check if objectid is valid
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
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))