user2069136
user2069136

Reputation: 289

Handlebars, JS and Node

I'm trying to get hold of the data sent by the server from a MongoDB. A regular GET:

.get('/test', function(req, res){
  mongo.collection('collection').find({ _id:req.user._id.toString()
    }).toArray( function(err, doc){
        res.render('partials/map', 
          { docs : doc });
      }
    });      
});

I.e. sending an array with the documents to the client. Then I want to manipulate the data on the client side so I, in the javascript on the client do:

<script>
  var docs = '{{docs}}';
  console.log(typeof(docs));
  console.log(docs);

  var obj = new Object(docs);
  console.log(obj);

  var arr = new Array(docs);
  console.log(arr);

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

</script>

However, I can't figure out how to actually manipulate it as the above just gives me the following outputs (in the console):

string
[object Object],[object Object],[object Object]
String {"[object Object],[object Object],[object Object]"}
["[object Object],[object Object],[object Object]"]
"[object Object],[object Object],[object Object]"

How can I manipulate the data? I know it's an array with three documents but just trying docs[0] gives the first character in [object Object] (i.e. "["). Also, a JSON.parse(docs) just returns error as docs somehow already is an object.

Upvotes: 0

Views: 67

Answers (1)

JJJ
JJJ

Reputation: 3352

Stringify the object on the server and then access it on the client.

//server
res.render('partials/map', {docs: JSON.stringify(doc)})

//client
var docs = {docs}

Upvotes: 1

Related Questions