Search code examples
javascriptnode.jsexpress-handlebars

How to fix frontend javascript in handlebars catching undefined value from server?


I have a JSON object in backend which I want to send to frontend javascript. But I'm constantly encountering "undefined" when trying to access that variable.

candidates is json object and is working fine in server side.

Here's my server side code.

res.render('electionview',{title: 'Election', poll: poll, data: JSON.stringify(candidates) });

Here's my script in Handlebars

<script type="text/javascript">
var candidates = {{{data}}};
console.log(candidates);
<script>

But I'm getting this error in console.

Uncaught SyntaxError: Unexpected token ';'

When I remove semicolon, output in the console is undefined. What am I missing ?


Solution

  • I was getting candidates as:

    Candidate.find({}).lean()
           .then(candidates=>res.render("electionview", JSON.stringify(candidates))
    

    Removing .lean() fixed it.