dimanche 8 mars 2015

Returning the results of an mysql-query. Ends up returning undefined

I have a function that queries my database and returns the results. However whatever I return, it is undefined.


Server-code: I call my function here



var express = require('express');
var DBmodule = require('./db.js');
var router = express.Router();

router.get('/topics', function(req,res){
res.send(DBmodule.getTopics()); //Call to db.js - This returns undefined
});


db.js code



var mysql = require('..\\node_modules\\mysql');

var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password'
});

exports.getTopics = function(){
connection.connect();
connection.query('USE db');
var strQuery = "SELECT * FROM topics";

connection.query(strQuery, function(err, rows){
if(err){
throw err;
}else{
return rows;
}
});

connection.end();
};


The thing that has me confused is that if I console.log rowswhen in the getTopics function, I get the correct results. But in the server code, all I get is undefined.


From my searching I figured it might have something with callback to do, but I could not get it to work anyway. Any advice?


Aucun commentaire:

Enregistrer un commentaire