NodeJS中的BSON对象的console.log
我很困惑的方式console.log显示NodeJS的本地MongoDB驱动程序的ObjectId()对象。
我用console.log从MongoDB打印adslot
文档:
db.collection('adslots').findOne({_id: adslotId}, (err, adslot)=>{ console.log( adslot ); }
和输出是
adslot: { _id: 57ef0b9b26d1d77b606bf271, name: 'cspop', width: 1, height: 1, elemId: 'dummy', active: true, updated: 2016-10-01T01:04:27.597Z }
_id
看起来像一个hex数字。 但是,_id是ObjectId,因为:
console.log( "adslot:\n" + adslot._id.constructor.name );
给
adslot: ObjectID
尽pipeadslot
具有调用isValid()
( http://mongodb.github.io/node-mongodb native / 2.2 / api / ObjectID.html#.isValid)的ObjectId
构造函数,但它给出了一个错误:
console.log('adslot:'); console.log( adslot._id.isValid() );
结果:
adslot: /home/vlad/arbsrv/node_modules/mongodb/lib/utils.js:98 process.nextTick(function() { throw err; }); ^ TypeError: adslot._id.isValid is not a function
那么,为什么console.log()
_id
打印为数字而不是对象呢? toString()
以某种方式自动调用_id
?
为什么如果_id
是ObjectId
实例, isValid()
没有被定义呢?
isValid
是在ObjectId
本身上定义的,而不是它的原型。 ObjectId的一个实例不会有这个方法。 尝试将其称为ObjectId.isValid()
以下面的例子为例:
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
为什么console.log()将_id打印为数字而不是对象?
简短的回答,是的,它调用了toString()。 有关更多详细信息,请查看此答案 。 另外从我的理解,ObjectId原型有一个toString方法定义它返回_id值作为一个string。