0

I query data from a database and want to display it on my site. I decided to outsource my SQL statements into a seperat file called select.js. How can I pass the database data into my routes file and there on my site? Now it's always undefined. If I put the SQL select directly into my route then it works fine.

What I got so far:

select.js


const db = require('./config'); //Connection works 

//KATEGORIEN LADEN
var sql = 'SELECT * FROM Kategorie';
var Kategorie_data;
db.query(sql, function (err, data, fields) {
  if (err) throw err;
  Kategorie_data = data; //tried there playing a bit with the var data
});

module.exports = {
    kategorie_data: Kategorie_data,
}

snippet route.js

var express = require('express');
var router = express.Router();
var db = require('../query/select');

router.get('/api', function (req, res, next) {
    console.log(db.kategorie_data);
    res.render('api/api', {kategorie_data: db.kategorie_data });
});

api.ejs

<% if(kategorie_data.length!=0){
    var i=1;
        kategorie_data.forEach(function(data){
    %>
<%=data.Kategorie_Name %>
<%  i++; }) %>
<% } else{ %>
   No Data Found
<% } %>

2 Answers 2

1

select.js

const get_data=()=>{
  var sql = 'SELECT * FROM Kategorie';
  return new Promise((resolve,reject) => {
    db.query(sql, function (err, data, fields) {
      if (err) reject(err);
      resolve({data});
    });
  })
}
module.exports={
  get_data
}

router.js

  router.get('/api', (req, res, next) => {
    db.get_data()
      .then(({ data: kategorie_data }) => {
        res.render('api/api', { kategorie_data });
      })
      .catch((error) => {
        // do your thing
      });
  });
Sign up to request clarification or add additional context in comments.

Comments

0

The query function is asynchronous, using a callback. So at the time you create the export Kategorie_data is still undefined. Since the export is cached it is also not updated later on.

You can export a function which will execute the query for you:

var getKategorieData = function (callback){
  db.query(sql, callback);
}


module.exports = {
    kategorie_data: getKategorieData,
}

and then use it like this:

router.get('/api', function (req, res, next) {
    db.kategorie_data((err, data, fields)=>{
       if(error) //error handling
       else {
         res.render('api/api', {kategorie_data: data });
       }
    });
    res.render('api/api', {kategorie_data: db.kategorie_data });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.