JoyceChoi
JoyceChoi

Reputation: 11

Node.js db.query is not a function

I am using Node.js and Express, and I would like to query a MySQL database on AWS EC2.

I have created connection to the database in db_connection.js file and tried to export the connection (db) so I can use db.query() in other js files. I have confirmed that the connection is working (displays "Connected" in console) and when I put db.query() right after db.connect() in db_connection.js, it works.

The problem is that when I use db.query() in other files (e.g timetables.js), I receive "TypeError: db.query is not a function" error.

Could anyone tell me how to fix this? Thank you.

db_connection.js

let mysql = require('mysql2');
let Client = require('ssh2').Client;

let ssh = new Client();

process.on('uncaughtException', function (error) {
  console.log(error.stack);
});

ssh.on('ready', function () {
  ssh.forwardOut(
    '127.0.0.1',
    12345,
    '127.0.0.1',
    3306,
    function (err, stream) {
      if (err) {
        console.error('forwardOut Error: ' + err);
        return;
      }
      console.log('forwardOut: ready!');
      let db = mysql.createConnection({
        user: 'user',
        password: 'password',
        database: 'database',
        stream: stream
      });
      db.connect(function (err) {
        if (err) {
          console.error('error connecting: ' + err.stack);
          return;
        }
        console.log('Connected');
        module.exports = db;
      });
    });
}).connect({
  host: 'xxx.xxx.xxx.xxx',
  user: 'user',
  privateKey: require('fs').readFileSync('xxx.pem'),
  port: 22
});

timetables.js

let express = require('express');
let router = express.Router();
let db=require('../db_connection');

router.get('/mytimetable', function(req, res, next) {
  let sql='Select * FROM timetables T, courses C, classoptions O WHERE T.classoptid = O.classoptid AND O.cid = C.cid ORDER BY C.cid, O.classopttitle';
  db.query(sql, function (err, data, fields) {
  if (err) throw err;
  res.render('timetable', { title: 'Timetable', timetableData: data});
});
});
module.exports = router;

Upvotes: 0

Views: 6359

Answers (1)

JoyceChoi
JoyceChoi

Reputation: 11

I used the multiple callback way suggested in the link that buithienquyet provided. The error message no longer appears and the query is executed correctly.

Upvotes: 1

Related Questions