下面,您可以看到这两个日志的输出。第一行代码清楚地显示了我试图访问的属性的完整对象,但在下一行代码中,我无法使用配置访问它。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);
这就是这些行在控制台中打印的内容
当前回答
对我来说,这是一个与猫鼬有关的问题。
我正在循环从Mongo查询中得到的对象。我只需要删除:
items = await Model.find()
并将其替换为:
items = await Model.find().lean()
其他回答
您试图访问的属性可能还不存在。Console.log可以工作,因为它在一小段延迟后执行,但其余代码并非如此。试试这个:
var a = config.col_id_3; //undefined
setTimeout(function()
{
var a = config.col_id_3; //voila!
}, 100);
我的数据只是json数据字符串。(这个变量在会话中存储为json字符串)。
console.log(json_string_object)
->只返回该字符串的表示形式,无法区分是string还是object。
所以为了让它工作,我只需要把它转换回真实对象:
object = JSON.parse(json_string_object);
我没有得到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\" }"
}
}
*/
我今天也遇到了同样的问题。在我的例子中,键是嵌套的,即key1.key2。 我使用split()分割键,然后使用方括号符号,这对我来说很有效。
var data = {
key1: {
key2: "some value"
}
}
我把键分开并像这样使用它,data[key1][key2]为我做了这项工作。
我刚刚从MongoDB使用Mongoose加载文档时遇到了这个问题。
当在整个对象上运行console.log()时,所有文档字段(存储在db中)都会显示出来。然而,当其他属性(包括_id)正常工作时,一些单独的属性访问器将返回undefined。
事实证明,属性访问器只适用于我的mongodb . schema(…)定义中指定的字段,而console.log()和JSON.stringify()返回存储在db中的所有字段。
解决方案(如果你正在使用Mongoose):确保你所有的db字段都是在Mongoose . schema(…)中定义的。