节点JS Inspect显示属性有价值,但检查属性返回未定义
我正在做一个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属性是一个包含键的对象,其中包含一个指示是否应该加载模块的布尔值(请参阅本文后面的console.log输出)。 以下四个属性是特定模块的设置。
当我的应用程序启动时,我为当前用户加载这些信息,并将数据分配给一个像这样的configurationvariables:
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
现在,前三个模块完美地工作。 我一个星期前编了一遍,没有错。 但是现在我正在添加数据types模块,并且遇到了一个非常奇怪的问题。
每当我尝试访问clients[0].datatypes
属性它返回undefined
但是当我做console.log clients[0]
它会显示我所有的属性,及其值,包括数据types。
console.log clients[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] } }
所以如你所见,这里有所有的属性,包括数据types。 这些我可以访问模块,报告,filter和模板属性没有任何问题(例如使用clients[0].modules
),但是当我想要访问数据types属性clients[0].datatypes
它将返回undefined
。
我有三重检查,我正在写'数据types',这不是一个asynchronous函数,与我混淆。 我把日志放在我实际上想要使用.datatypes的行之前,并没有asynchronous的东西正在进行,所以不是这样。 我尝试了一些其他的东西,改变加载顺序等,但没有任何工作。
console.log clients[0] console.log clients[0].datatypes
第一行输出我的整个对象,包括数据types属性。 第二个一直说undefined
。
我认为这可能与Node或Mongoose有关,也可能是Javascript怪癖之一,也可能(只是可能),只是我是一个白痴,弄乱了某些东西。 我真的不知道,我一直在寻找解决scheme,现在大约两个小时,做了一百个谷歌search的东西,去挖通过StackOverflow和其他网站,但我找不到我的问题的答案,couldn我自己解决。 有没有人知道可能是什么原因造成这个问题?
对于任何有这个问题的人来说,我的修正是在Mongoose结果上调用.toObject()
: client[0] = client[0].toObject()
。 这将Mongoose对象转换为常规对象。
对我来说,为什么所有其他的财产都可以在没有这个的情况下得到处理,这仍然是一个谜。 但.toObject()
解决了这个问题。