Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/46.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js NodeJS中BSON对象的console.log_Node.js_Mongodb_Bson - Fatal编程技术网

Node.js NodeJS中BSON对象的console.log

Node.js NodeJS中BSON对象的console.log,node.js,mongodb,bson,Node.js,Mongodb,Bson,我对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',

我对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 }
\u id
看起来像一个十六进制数。但是,\u id是ObjectId,因为:

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

尽管有
adslot
的构造函数
ObjectId
调用
isValid()
(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()
\u id
打印为数字而不是对象?在
\u id
上是否自动调用了
toString()


如果
\u id
ObjectId
的实例,那么为什么它没有定义
isValid()
。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()将\u id打印为数字而不是对象?


简单回答,是的,它调用它的toString()。有关更多详细信息,请查看此页。根据我的理解,ObjectId原型上定义了一个toString方法,该方法以字符串形式返回_id值。

根据您提到的答案:“FF中的控制台API仅在参数类型不是{undefined,null,object,set,map}类型时才对参数调用toString()。”但typeof _id返回“object”所以我不明白为什么console.log()会自动调用它的toString()。它是NodeJs中Objectid()对象的特殊补丁吗?好的,isValid是Objectid的静态方法,用作Objectid.isValid(adslot.\u id),返回true。关于console.log的问题仍然存在。
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