statice
statice

Reputation: 35

Convert data returned by mongoose to json

I am printing my entire collections with this piece in routes/index.js

exports.create = function(req,res){
new checklist_model({
        name : req.body.name,
                comment : req.body.comment
               }).save(function(err,checklist_model){
        res.redirect('/');
        });
};

    exports.checklist = function ( req, res ){ 
      checklist_model.find({},function ( err,checklist_data,count ){
        res.render( 'checklist', {
          title : 'checklist',
          checklist_data : JSON.stringify(checklist_data)
        });console.log(checklist_data);
      });
    };

I get the collection data in the format below:

{ name: 'Stats',
    comment: 'Functionality test',
    _id: 53c5f7cdb79a40232193c45e,
    __v: 0 }

How do I get this to print in JSON format?

{ "name": "Stats",
    "comment": "Functionality test",
    "_id": "53c5f7cdb79a40232193c45e",
    "__v": "0" }

Thanks

EDIT: Soulcheck made a great suggestion about converting data to json and it "works", but when i try to use "checklist_data" from code( mentioned above under routes/index.js) in my checklist.jade nothing is happens. (I am trying to use script tags first, just to understand how it actually works)

<script language="javascript" class="lookhere">
  var myJason = JSON.parse(checklist_data);
  var result = myJason.row;
  console.log(result);
  for (var i = 0; i < result.length; i++)
      {
         var object = result[i];
         for (property in object)
         {
               var value = object[property];
               alert(property + "=" + value);
         }
      }
</script>

checklist.jade:

| doctype html
| html.
  head
    meta(charset='UTF-8')
    title Example of Twitter Bootstrap 3 Vertical Form Layout
    link(rel='stylesheet', href='http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css')
    link(rel='stylesheet', href='http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css')
    script(src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js')
    script(src='http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js')
    style(type='text/css')
      .bs-example{
      margin: 20px;
      }
  body
    form.bs-example(action='/create', method='post')
      .form-group
        label(for='name')
        input#name.form-control(type='text', placeholder='Enter Name', name='name')
        label(for='name')
        textarea.form-control(rows='3', name='comment') Enter Comments
      button.btn.btn-default(type='submit') Submit
    script.lookhere(language='javascript')
      var myJason = JSON.parse(checklist_data);
      var result = myJason.row;
      console.log(result);
      for (var i = 0; i < result.length; i++)
      {
      var object = result[i];
      for (property in object)
      {
      var value = object[property];
      alert(property + "=" + value);
      }
      }

EDIT_2:

My JSON populates like this below

 var myJason = JSON.parse([{&quot;name&quot;:&quot;test&quot;,&quot;comment&quot;:&quot;testing&quot;,&quot;_id&quot;:&quot;53ceccae51f13e5f2d9003db&quot;,&quot;__v&quot;:0}]);

and i get the error just after this line.

:3004/:25Uncaught SyntaxError: Unexpected token &

Upvotes: 1

Views: 5650

Answers (1)

soulcheck
soulcheck

Reputation: 36777

What seems to be your problem is the fact that you're mixing the ways the object is represented.

When you do console.log(data) you probably get:

{ 
     name: 'Stats',
     comment: 'Functionality test',
     _id: 53c5f7cdb79a40232193c45e,
     __v: 0 
}

This is correct - console.log doesn't serialize objects to JSON, it serializes them as javascript object literals instead (and other related strings for arrays, functions, etc).

Now the JSON.stringify(checklist_data) call will almost certainly give you the desired result, that is:

{ "name": "Stats",
"comment": "Functionality test",
"_id": "53c5f7cdb79a40232193c45e",
"__v": "0" }

Now if you want to print the actual JSON, use:

console.log(JSON.stringify(checklist_data));

You were almost there in your code, but you called console.log with not yet serialized object.

edit Ok looking at your code you're better off not deserializing from JSON at all.

So in your node code do:

   res.render( 'checklist', {
      title : 'checklist',
      checklist_data : Json.stringify(checklist_data)
   })

and then in your jade template:

  script.lookhere(language='javascript')
  var myJason = !{checklist_data};
  var result = myJason.row;
  console.log(result);
  for (var i = 0; i < result.length; i++)
  {
  ....

Remember, JSON is a valid javascript object literal.

Upvotes: 1

Related Questions