convert mongodb object to javascript object

≡放荡痞女 提交于 2021-02-08 10:54:17

问题


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}
      ]
    }

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]

if I tried to print the text by using JSON.stringify(), I get the following result

[{"of":23}]

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)

and get the error

SyntaxError: Unexpected token _ in JSON at position 2

回答1:


If you use mongoose, I think that the correct form is using ToJSON() function.

Otherwise, you can use JSON.parse(JSON.stringify(data)); But I think that de first form is better.

=)




回答2:


Alternatively you could use .toObject() method from javascript to convert mongoose object into javascript object.

Here is a reference link to dig out more

https://alexanderzeitler.com/articles/mongoose-tojson-toobject-transform-with-subdocuments/



来源:https://stackoverflow.com/questions/49508700/convert-mongodb-object-to-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!