0

I am trying to pass a SQLite request stored into a variable to a pug template. My program works fine if using a string value passed to my pug view. But i always get an empty or undefined variable in my html when using the stored request result. I ve been reading many posts and tried multiple explanations but i still cant figure out what is wrong with my code.

Here is my server code

router.get('/mydata', function(req, res){   
    
    var sqlite3 = require('sqlite3').verbose();
    var mydb = new sqlite3.Database('mydb');
    var data = {};
    
    mydb.serialize(function() {
    var rowset = mydb.each("SELECT * FROM mytable", function(err, row) {
        data[row.id] = {
        name: row.name,
        };
        res.render('mydata', { 
            data: data
   });
  });
 });
});

here is my pug code

script.  
    var data = data
 

Precision : object data is fine when i print it on the server side.

Thanks a lot for any help (and sorry if it s an asynch beginer issue...)

toma
  • 1
  • Possible duplicate of [How to pass variable from jade template file to a script file?](http://stackoverflow.com/questions/8698534/how-to-pass-variable-from-jade-template-file-to-a-script-file) – Iso May 02 '17 at 08:35
  • 1
    Change your Pug code with like this: ```script var data = !{JSON.stringify(data)}``` – ozgrozer Sep 30 '17 at 13:03

1 Answers1

1
// db.js
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('mydb');
...
module.exports = db;

// routers
var db = require('db');

router.get('/mydata', function(req, res, next) { // add error handler
    db.all('select * from mytable', function(err, rows) {
        if (err)
            return next(err);

        var data = {};
        rows.forEach(function(row) {
            data[row.id] = row.name
        });

        res.render('mydata', {data}); 
    })
});
Aikon Mogwai
  • 4,954
  • 2
  • 18
  • 31