0

I have this express application with mongoDB as the database and handlebars as my server-side templating engine. I am not using AngularJS or Ajax in my application.

In one of the routes, I have to render the page as well as send over a json file from the database. However, I am not able to achieve this.

This is my code snippet from by route:

router.get('/disks', function(req, res, next) {

      var risime;

  places.find({"category": "disks"}, function(err, disk){
      if(err){
        throw err;
      }

      risime= disk;
      console.log(risime);  //PROPERLY LOGS THE OUTPUT

  });

  res.render('diskPage', 
    {
      'disks': risime
    });

});

In the hbs, I am trying to capture it, but I am not getting the json data:

  var clrisime= "{{risime}}"
  console.log(clrisime); // DOES NOT LOG ANYTHIN

How do I make it happen?

isvforall
  • 8,768
  • 6
  • 35
  • 50
QuikProBroNa
  • 796
  • 2
  • 7
  • 25

2 Answers2

5

You made two simple mistakes:

router.get('/disks', function(req, res, next) {

  var risime;

  places.find({"category": "disks"}, function(err, disk){
      if(err){
        throw err;
      }

      risime= disk;
      console.log(risime);  //PROPERLY LOGS THE OUTPUT

      // this belongs inside your db callback
      res.render('diskPage', 
        {
          'disks': risime
          // if you call your field 'disks' here, you need to write {{disks}} in your template
        });
  });


});
  1. Since your want to use the database result in your response, you need to put the res.render inside the callback.
  2. The variable name inside your template and the field name of the render object must be the same.
Nick D
  • 1,483
  • 1
  • 13
  • 22
1

Your code is executed asynchronously. It means places.find and res.render are executed almost in same time (~10ms max) and the render is done before the place.find. So you don't have the data in the render, logically.

You must place your second part of the code inside the callback of the resolution of your first condiiton (places.find) as in :

router.get('/disks', function(req, res, next) {
  var risime;
  places.find({"category": "disks"}, function(err, disk){
  if(err){
    throw err;
  }
  risime= disk;
  console.log(risime);  //PROPERLY LOGS THE OUTPUT
  res.render('diskPage', 
  {
    'disks': risime
  });
});

And it will works if you use {{disks}} instead of {{risime}} in your view.

Aethyn
  • 695
  • 1
  • 4
  • 16