将 mongodb 对象转换为 javascript 对象 [英] convert mongodb object to javascript object
问题描述
我在启动时将配置文件传递给另一个 node.js 模块.配置文件包含以下 json:
I pass a config file to another node.js module when starting it. The config file contain the following json:
"resolution": {
"activated": true,
"types": [
{"of": 23}
]
}
当我在被调用的 node.js 模块中打印接收到的类型数组时,它看起来像
When I print the received types array in the called node.js module, it looks like
console.log('types array: '+ this.config.resolution.types)
//output
types array: [object Object]
如果我尝试使用 JSON.stringify()
打印文本,我会得到以下结果
if I tried to print the text by using JSON.stringify()
, I get the following result
[{"of":23}]
当我尝试用从 mongodb 数据库重试的列表替换 types 数组时,我的问题就开始了.我的代码看起来像:
My problem start when I try to replace the types array with a list retried from a mongodb database. my code looks like:
分辨率":{激活":真,类型":[保存类型]}
"resolution": { "activated": true, "types": [ savedTypes ] }
现在当我打印收到的类型配置时,它看起来像这样:
Now when I print the received types config, it looks like this:
types array: { _id: 5ab9fe8fd1f64303cd98f122, of: 23, __v: 0 }
并且被调用的节点模块在此配置下无法正常工作.我怎样才能把它投射到一个对象上?我尝试使用
and the called node module is not working properly with this config. How can I cast this to an object? I tried to use
JSON.parse(savedTypes)
并得到错误
SyntaxError: Unexpected token _ in JSON at position 2
推荐答案
如果你使用 mongoose,我认为正确的形式是使用 ToJSON() 函数.
If you use mongoose, I think that the correct form is using ToJSON() function.
否则,您可以使用 JSON.parse(JSON.stringify(data));但我认为第一种形式更好.
Otherwise, you can use JSON.parse(JSON.stringify(data)); But I think that de first form is better.
=)
这篇关于将 mongodb 对象转换为 javascript 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!