Insert JSON.Stringified data in MongoDB

var obj = {}; obj.url = hostNames[i]; obj.statusCode = res.statusCode; obj.headers = res.headers; db.collection.save(JSON.stringify(obj, null, 2)); 

I am currently trying to request an HTTP response through Node.js and then parse this output into MongoDB using JSON.stringify (a method that converts data to a JSON document format). For some reason, I get some weird output in MongoDB, it looks something like this:

 > db.scrape.find() { "_id" : ObjectId("51472849650593014a3c20da"), "0" : "{", "1" : "\n", "2" : " ", "3" : " ", "4" : "\"", "5" : "u", "6" : "r", "7" : "l", "8" : 

I believe that it interprets each char as a new variable. What have I done wrong in my code?

+4
source share
3 answers

why contract an object? The API expects a javascript object.

Just do:

 db.collection.save(obj); 
+8
source

Have you checked the output of JSON.stringify (obj, null, 2)? I think this will return the expected result.

There are two possible causes for this error: The way the document is stored is the wrong or the wrong way to get the document

At http://docs.mongodb.org/manual/tutorial/getting-started/ (running mongodb) there is no mention of converting documents to json before invoking the insert or something else.

Have you tried storing it as db.collection.save ({'content': JSON.stringify (obj, null, 2)}) ;?

+1
source

I had the same problem in a Meteor project. "response" is a string containing data in json format. The save method does not work. I created a new document simply:

  obj = JSON.parse(response); db.collection.insert(obj); 
+1
source

All Articles