我对 console.log 显示来自 NodeJS 的 native 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
看起来像一个十六进制数。但是,_id 是 ObjectId,因为:
console.log( "adslot:\n" + adslot._id.constructor.name );
给予
adslot:
ObjectID
尽管 adslot
具有调用 isValid()
的 ObjectId
构造函数(http://mongodb.github.io/node-mongodb native/2.2/api/ObjectID.html# .isValid ) 给出错误:
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
本身而非其原型(prototype)上定义的。 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() 。有关详细信息,请查看此 SO answer .同样据我所知,ObjectId 原型(prototype)上定义了一个 toString 方法,该方法将 _id 值作为字符串返回。
关于node.js - NodeJS 中 BSON 对象的 console.log,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41400075/