Skip to content


Subversion checkout URL

You can clone with
Download ZIP


Fix, an object with type ObjectID should be able to convert itself #71

merged 1 commit into from

2 participants


I propose this small addition to ObjectID, so that when used as a caster, it does not throw an exception.

Example :

var myObjectId = new ObjectID();
var idWithUnknownType = myObjectId;
// Some code later, use ObjectID() to force the type
idWithUnknownType = ObjectID(idWithUnknownType);

The above code works with basic javascript types, like Object, String, Number, but not ObjectID

MongoDB BSON ObjectID is used in many third party code that deals with serialization, database callbacks, string IDs, etc, which would make it handy if the ObjectID type can cast itslef, in many cases.

I included a test case for this behaviour, not sure if it's at the right place.

The fact that the whole test suite ran without a glitch let me propose this pullback. Let me know if there is a reason why ObjectID cannot be enhanced with this behaviour. Thanks !

@christkv christkv merged commit 6ff7867 into mongodb:master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Feb 23, 2014
  1. @pandaiolo
This page is out of date. Refresh to see the latest.
Showing with 16 additions and 0 deletions.
  1. +1 −0  lib/bson/objectid.js
  2. +15 −0 test/node/bson_test.js
1  lib/bson/objectid.js
@@ -24,6 +24,7 @@ var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
var ObjectID = function ObjectID(id) {
if(!(this instanceof ObjectID)) return new ObjectID(id);
+ if((id instanceof ObjectID)) return id;
this._bsontype = 'ObjectID';
var __id = null;
15 test/node/bson_test.js
@@ -129,6 +129,21 @@ exports['Should Correctly create ObjectID and do deep equals'] = function(test)
* @ignore
+exports['Should Correctly convert ObjectID to itself'] = function(test) {
+ var myObject, newObject;
+ var selfConvertion = (function() {
+ myObject = new ObjectID();
+ newObject = ObjectID(myObject);
+ });
+ test.doesNotThrow(selfConvertion);
+ test.equal(myObject, newObject);
+ test.done();
+ * @ignore
+ */
exports['Should Correctly get BSON types from require'] = function(test) {
var _mongodb = require('../../lib/bson');
test.ok(_mongodb.ObjectID === ObjectID);
Something went wrong with that request. Please try again.