Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert mongodb object to javascript object

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
like image 531
j.doe Avatar asked Sep 17 '25 07:09

j.doe


2 Answers

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.

=)

like image 181
aperdizs Avatar answered Sep 19 '25 20:09

aperdizs


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/

like image 24
Maaz Jawaid Avatar answered Sep 19 '25 20:09

Maaz Jawaid