2
votes

I'm confused about the way console.log displays ObjectId() objects from native MongoDB driver for NodeJS.

I print the adslot document from MongoDB with console.log:

db.collection('adslots').findOne({_id: adslotId}, (err, adslot)=>{
    console.log( adslot );
}

and the output is

adslot:
{ _id: 57ef0b9b26d1d77b606bf271,
  name: 'cspop',
  width: 1,
  height: 1,
  elemId: 'dummy',
  active: true,
  updated: 2016-10-01T01:04:27.597Z }

_id looks like a hex number. However, _id is ObjectId because:

console.log( "adslot:\n" + adslot._id.constructor.name );

gives

adslot:
ObjectID

In spite of adslot having constructor of ObjectId calling isValid() ( http://mongodb.github.io/node-mongodb native/2.2/api/ObjectID.html#.isValid ) on it gives an error:

console.log('adslot:');
console.log( adslot._id.isValid() );

results:

adslot:
/home/vlad/arbsrv/node_modules/mongodb/lib/utils.js:98
    process.nextTick(function() { throw err; });
                                  ^

TypeError: adslot._id.isValid is not a function

So, why does console.log() prints _id as a number and not as an object? Is toString() somehow called automatically on the _id?

And why if _id is instance of ObjectId, isValid() is not defined on it?

1
Ok, isValid is static method of ObjectId and is used as ObjectId.isValid(adslot._id) which returns true. The question about console.log remains.rlib

1 Answers

0
votes

isValid is defined on the ObjectId itself and not its prototype. An instance of the ObjectId will not have this method. Try calling it as ObjectId.isValid()

Take the following for example:

function ObjectId(){}

ObjectId.isValid = function(){
    return true;
}

ObjectId.prototype.sayHi = function(){
    return 'hello';
}

var a = new ObjectId();
a.sayHi(); // hello
a.isValid(); // raises exception

ObjectId.isValid(); // true

why does console.log() prints _id as a number and not as an object?

Short answer, yes it calls the toString() on it. For more details check this SO answer. Also from what i understand, the ObjectId prototype has a toString method defined on it which return the _id value as a string.