MongoDB Node check if objectid is valid

mongodb objectid
mongoose objectid is valid
mongodb objectid nodejs
mongodb check valid objectid
mongodb _id string
objectid is not defined mongodb
mongodbbsonobjectid
mongodb objectid regex

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'


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

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("badobjectid")
// false
checkForHexRegExp.test("5e63c3a5e4232e4cd0274ac2")
// true

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

Best way to validate an ObjectId � Issue #1959 � Automattic/mongoose, I'm checking to see if they refer to valid objects by just doing a find() call. node gh-1959.js error { CastError: Cast to ObjectId failed for value� If about.id is a string representation of an ObjectID and user.friends is an array of ObjectIDs, you can check if about.id is in the array using Array#some:. var isInArray = user.friends.some(function (friend) { return friend.equals(about.id); });


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))

ObjectID() — MongoDB Node.JS Driver 1.4.9 documentation, Return the ObjectID id as a 24 byte hex string representation a new ObjectID var objectId = new ObjectID(); // Verify that the hex string is 24 characters Returns: boolean return true if the value is a valid bson ObjectId, return false otherwise. node.js - nodejs - MongoDB Node check if objectid is valid node js mongodb find by id (4) 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.


As an extension of Eat at Joes answer... This is valid in node-mongodb-native 2.0

var objectID = require('mongodb').ObjectID

objectID.isValid('54edb381a13ec9142b9bb3537') - false
objectID.isValid('54edb381a13ec9142b9bb353') - true
objectID.isValid('54edb381a13ec9142b9bb35') - false

[SOLVED]Checking if input is an ObjectId in Mongo, isValid() . stackoverflow.com � Will. Can I determine if a string is a MongoDB ObjectID? javascript, node.js,� The merged & modified code accepts null and undefined as valid ObjectID.. These are indeed valid values for the ObjectID constructor, but they don't represent a specific ObjectID (ObjectID(null) generates a new ObjectID with generate() using current date), contrary to all other values (12 or 24 bytes long string) that designate a unique ObjectID, thus I'd think they should not be accepted by


@GianPaJ's snippet is great but it needs to be extended slightly to cover non hex objectID's. Line 32 of the same file indicates objectID's can also be 12 characters in length. These keys are converted to a 24 character hex ObjectID by the mongodb driver.

function isValidObjectID(str) {
  // coerce to string so the function can be generically used to test both strings and native objectIds created by the driver
  str = str + '';
  var len = str.length, valid = false;
  if (len == 12 || len == 24) {
    valid = /^[0-9a-fA-F]+$/.test(str);
  }
  return valid;
}

MongoDB Node check if objectid is valid - node.js - html, How can I check whether an ObjectID is valid using Node's driver I tried : var BSON = mongo.BSONPure; console.log("Validity: " + BSON.ObjectID. To proof wether you have a valid ObjectId, read the following SO-Post: MongoDB Node check if objectid is valid. EDIT: the final answer was: You have to change [BsonRepresentation(BsonType.ObjectId)] to [BsonId]


If you are using mongoose then you can use mongoose for validation rather than depending on any other library.

if (!mongoose.Types.ObjectId.isValid(req.id)) {
    return res.status(400).send("Invalid object id");
}

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')). type conversion, convert to ObjectId, ObjectId conversion, aggregation. Behavior¶. The following table lists the input types that can be converted to an ObjectId:


bson-objectid, Construct ObjectIDs without the mongodb driver or bson module. Checks if a value is a valid ObjectID or 24 character hex string. THE NATIVE DOCUMENTATION ISN'T CLEAR ON THIS GUY! Test. mocha. or npm test� Because "zzzzzzzzzzzz" is technically a valid ObjectId - an object id's only defining feature is that its 12 bytes long. See mongodb/js-bson#112. A JS string of length 12 has 12 bytes, modulo unicode weirdnesses. If you want to check for a length 24 hex string, just check the string matches /^ [a-fA-F0-9] {24}$/


ObjectId — MongoDB Manual, Hexadecimal string value for the new ObjectId. Methods and Attributes�. ObjectId () has the following attribute and methods:� If you start from scratch, create a new folder with your terminal and run npm init -y to start up a new Node.js project, and then run the npm install mongodb command. Connecting to MongoDB. You require the mongodb package and you get the MongoClient object from it.


Comparing mongoose _id and strings, ObjectID it requires the mongodb-native library and you can check if results. userId is a valid identifier with results.userId instanceof ObjectID. isValid() dans le js-bfils bibliothèque, qui est une dépendance de node-mongodb-natif. pour quiconque trouve cette question, Je ne recommande pas de recréer cette méthode comme recommandé dans d'autres réponses. Au lieu de cela, continuez à utiliser node-mongodb-native comme l'affiche originale l'utilisait, l'exemple suivant accédera au