4
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 attempting to request a HTTP response via Node.js, and then parsing that output into a MongoDB with JSON.stringify (a method that transforms things into JSON document format). For some reason, I am getting some weird output in MongoDB, it goes something like this:

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

What I think it is doing is that it is interpreting each char as a new variable. What did I do wrong in my code?

2
  • 3
    I'm a bit confused here: why are you trying to store a JSON-string, and not a document itself? As Mongo expects you to provide a document, it does the only more-o-less sensible thing to the string provided - parses it as an array. You should have at least store it like... db.collection.save({res: JSON.stringify(obj, null, 2)});. But, frankly speaking, you're trying to do the Mongo's work here: why not format this object when you output it? Commented Mar 18, 2013 at 14:59
  • Thanks for the reply. I am thinking, it would just be more convenient to have JSON.stringify() to format the import. What would you do in my case? Keep in mind I have three objects url, statusCode, and headers per "website". The url is the primary key for each "website" response. Commented Mar 18, 2013 at 15:06

3 Answers 3

8

why stringify the obj? the API expects a javascript object.

Just do:

db.collection.save(obj);
Sign up to request clarification or add additional context in comments.

1 Comment

It has been deprecated. Is there any other way ?
1

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

There are two possible reasons for this error: The way of storing the document is wrong or the way the document is retrieved is wrong

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

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

Comments

1

I had the same problem in a Meteor project. "response" is a string that contains data in json format. "save" method didn't work. I created a new document simply by:

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

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.