下面,您可以看到这两个日志的输出。第一行代码清楚地显示了我试图访问的属性的完整对象,但在下一行代码中,我无法使用配置访问它。Col_id_3(见截图中的“undefined”?)有人能解释一下吗?我也可以访问除field_id_4之外的所有其他属性。
console.log(config);
console.log(config.col_id_3);
这就是这些行在控制台中打印的内容
下面,您可以看到这两个日志的输出。第一行代码清楚地显示了我试图访问的属性的完整对象,但在下一行代码中,我无法使用配置访问它。Col_id_3(见截图中的“undefined”?)有人能解释一下吗?我也可以访问除field_id_4之外的所有其他属性。
console.log(config);
console.log(config.col_id_3);
这就是这些行在控制台中打印的内容
当前回答
我没有得到MongoDB错误消息在抛出错误在我的NodeJS API响应,所以我做了以下工作
// It was not working
console.log(error.message) // prints the error
let response = error;
// message property was not available in the response.
/*
{
"status": "error",
"error": {
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"keyPattern": {
"event_name": 1
},
"keyValue": {
"event_name": "followup"
}
}
}
*/
// so I did this
let message = error.message;
let response = JSON.parse(JSON.stringify(error));
response.message = message;
// message property is now available in the response.
/*
{
"status": "error",
"error": {
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"keyPattern": {
"event_name": 1
},
"keyValue": {
"event_name": "followup"
},
"message": "E11000 duplicate key error collection: mycollections.notificationevents index: event_name_1 dup key: { event_name: \"followup\" }"
}
}
*/
其他回答
我也有类似的问题,希望下面的解决方案能帮助到别人。 你可以使用setTimeout函数,但你永远不知道你的浏览器需要多长时间来定义你的对象。
除此之外,我建议使用setInterval函数。它将等待您的对象配置。Col_id_3被定义,然后触发需要特定对象属性的下一个代码部分。
window.addEventListener('load', function(){
var fileInterval = setInterval(function() {
if (typeof config.col_id_3 !== 'undefined') {
// do your stuff here
clearInterval(fileInterval); // clear interval
}
}, 100); // check every 100ms
});
我刚刚从MongoDB使用Mongoose加载文档时遇到了同样的问题。
原来,我使用属性find()只返回一个对象,所以我把find()改为findOne(),一切都为我工作。
解决方案(如果您正在使用Mongoose):确保只返回一个对象,这样您就可以解析它的对象。Id或者它将被视为数组所以你需要像访问对象[0]。Id那样访问它。
2018年,Mozilla在Mozilla文档中警告我们!
我引用“日志对象”:
不要使用console.log(obj); 使用console.log (JSON.parse (JSON.stringify (obj)));。 通过这种方式,您可以确定当前正在看到obj的值 你记录下来。
我也面临同样的问题。
从服务器,我在json_encode中返回数据。 像这样
echo json_encode($res);
当我返回一个不带json_encode的简单PHP数组后,问题就解决了。
return $res;
我遇到过这样的问题,发现解决方案与Underscore.js有关。我最初的日志记录毫无意义:
console.log(JSON.stringify(obj, null, 2));
> {
> "code": "foo"
> }
console.log(obj.code);
> undefined
我还通过查看对象的键找到了解决方案:
console.log(JSON.stringify(Object.keys(obj)));
> ["_wrapped","_chain"]
这让我意识到obj实际上是一个围绕对象的Underscore.js包装器,最初的调试对我撒谎了。