我正在开发一个 Node JS 应用程序,使用 Coffeescript 和 Mongoose 以及 MongoDB 数据库。
我有一个像这样的 Mongoose 模型:
Client = mongoose.model 'Client', mongoose.Schema
# Basics
name: String
email: String
api_key: String
# Modules enabled / disabled
modules: Object
# Settings for modules
reporting: Object
filter: Object
templates: Object
datatypes: Object
modules 属性是一个对象,其中包含带有 bool 值的键,指示是否应加载模块(请参阅本文中的 console.log 输出)。下面的四个属性是特定模块的设置。
当我的应用程序启动时,我为当前用户加载此信息,并将数据分配给配置变量,如下所示:
config.name = clients[0].name
config.api_key = clients[0].api_key
config.modules =
reporting_enabled: clients[0].modules.reporting
filter_enabled: clients[0].modules.filter
templates_enabled: clients[0].modules.templates
datatypes_enabled: clients[0].modules.datatypes
现在,前三个模块可以完美运行。我大约一周前对它们进行了编码,没有任何问题。但我现在添加数据类型模块,遇到了一个非常奇怪的问题。
每当我尝试访问 clients[0].datatypes
属性时,它都会返回 undefined
但当我执行 console.logclients[0]
时,它会向我显示所有属性及其值,包括数据类型。
console.logclients[0]的部分输出:
modules:
{ datatypes: true,
templates: true,
filter: false,
reporting: true },
reporting:
{ email_interval: 2,
name: '___',
email: '___',
send_email: true },
filter: {},
templates: { cms: { contacts: [Object] } },
datatypes: { cms: { contacts: [Object] } }
正如您所见,有包括数据类型在内的所有属性。其中,我可以毫无问题地访问模块、报告、过滤器和模板属性(例如使用 clients[0].modules
),但是当我想访问数据类型属性 clients[0].datatypes
时,它将返回 undefined
。
我已经三重检查,确保我正确地编写了“数据类型”,并且它不是一个困扰我的异步函数。我将日志放在我实际想要使用 .datatypes 的行之前,并且此时没有发生异步内容,所以不是这样。我尝试了其他一些方法,更改加载顺序等,但没有任何效果。
console.log clients[0]
console.log clients[0].datatypes
第一行输出我的整个对象,包括数据类型属性。第二个一直说未定义
。
我认为这可能与 Node 或 Mongoose 有关,或者它是 Javascript 怪癖之一,或者也许(同样可能)只是我是个白痴,把事情搞砸了。我真的不知道,我已经搜索了大约两个小时的解决方案,进行了一百次谷歌搜索,在 StackOverflow 和其他网站上进行了挖掘,但我找不到问题的答案,也无法自己解决它。这里有人知道可能导致此问题的原因吗?
最佳答案
对于遇到此问题的其他人,我的解决方法是调用 .toObject()
Mongoose 结果:client[0] = client[0].toObject()
。这会将 Mongoose 对象转换为常规对象。
对我来说,为什么所有其他属性都可以在没有这个的情况下得到很好的解决,但有一个属性却不能,这仍然是一个谜。但是 .toObject()
为我解决了这个问题。
关于javascript - Node JS Inspect 显示属性具有值,但检查属性返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31706266/