j.doe
j.doe

Reputation: 4859

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

Upvotes: 4

Views: 13783

Answers (2)

Maaz Jawaid
Maaz Jawaid

Reputation: 51

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/

Upvotes: 3

aperdizs
aperdizs

Reputation: 124

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.

=)

Upvotes: 5

Related Questions