Should I Parse JSON Data Before Inserting To MongoDB?

So, I am receiving some JSON data from a client to my Node.JS server. I want to insert that json into my MongoDB instance using Mongoose.

I can insert the JSON as-is, and it works great, because it's just text. However, I want to parse it before insertion so that when I extract it later it will be all nice and neat.

So, this works:

wordStream.words.push(wordData);

And this doesn't:

wordStream.words.push(JSON.parse(wordData));
  1. So, should I even want to parse the JSON before insertion?

  2. And if I should parse the JSON, how do I do it without throwing an error? I need to put everything in double quotes "", I believe, before it will parse, but for some reason whenever I make a string with double quotes and parse it, it turns everything all wrong.

Here is the JSON:

      { word: 'bundle',
          definitions:
           [ { definition: 'A group of objects held together by wrapping or tying.',
               partOfSpeech: 'noun' } ],
          urlSource: 'testurl',
          otherSource: '' }

And the error when I try to parse

/Users/spence450/Documents/development/wordly-dev/wordly-server/node_modules/mongoose/lib/utils.js:409
        throw err;
              ^
SyntaxError: Unexpected token o

Ideas?

So, should I even want to parse the JSON before insertion?

Convert the strings to JSON objects will benefit you later, when you need to make queries in your MongoDB database.

And if I should parse the JSON, how do I do it without throwing an error? I need to put everything in double quotes "", I believe, before it will parse, but for some reason whenever I make a string with double quotes and parse it, it turns everything all wrong.

You aren't receiving JSON documents. JSON documents must contain the keys quoted.

You can:

  • Use a library that recognizes invalid JSON objects (please don't)
  • Use eval (this is a security issue, so don't do it)
  • Fix the source of the problem, creating real JSON objects. This isn't difficult, you can see the JSON features here