4

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
  • Share your mongodb query. Commented Mar 27, 2018 at 9:16

2 Answers 2

5

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.

=)

Sign up to request clarification or add additional context in comments.

2 Comments

Why don't you use lean() in mongoose, user.find({}).lean() like this
@MariyaJames yes! it is right! =) but I don't know if he need mongoose objects.
3

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.