下面,您可以看到这两个日志的输出。第一行代码清楚地显示了我试图访问的属性的完整对象,但在下一行代码中,我无法使用配置访问它。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);
这就是这些行在控制台中打印的内容
当前回答
如果这是在使用Mongoose时发生的问题,则可能会发生以下情况:
console.log(object)
返回所有内容,包括所需的键。
console.log(object.key)
返回未定义。
如果发生了这种情况,就意味着Mongoose Schema中缺少键。添加它将解决这个问题。
其他回答
我也有同样的问题。我的解决方案是使用字符串化输出作为解析JSON的输入。这对我很管用。希望对你有用
var x =JSON.parse(JSON.stringify(obj));
console.log(x.property_actually_now_defined);
我也有类似的问题,希望下面的解决方案能帮助到别人。 你可以使用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错误消息在抛出错误在我的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\" }"
}
}
*/
检查对象内部是否有一个对象数组。我有一个类似的问题与JSON:
"terms": {
"category": [
{
"ID": 4,
"name": "Cirugia",
"slug": "cirugia",
"description": "",
"taxonomy": "category",
"parent": null,
"count": 68,
"link": "http://distritocuatro.mx/enarm/category/cirugia/"
}
]
}
我试图从“类别”访问“名称”键,我得到了未定义的错误,因为我正在使用:
var_name = obj_array.terms.category.name
然后我意识到它有方括号,这意味着它在category键中有一个对象数组,因为它可以有多个category对象。因此,为了获得'name'键,我使用了这个:
var_name = obj_array.terms.category[0].name
这就成功了。
也许现在回答这个问题已经太晚了,但我希望有同样问题的人能像我一样在找到解决方案之前找到这个答案:)
我今天也遇到了同样的问题。在我的例子中,键是嵌套的,即key1.key2。 我使用split()分割键,然后使用方括号符号,这对我来说很有效。
var data = {
key1: {
key2: "some value"
}
}
我把键分开并像这样使用它,data[key1][key2]为我做了这项工作。