Cleaning
Cleaning

Reputation: 65

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?

Upvotes: 0

Views: 4693

Answers (2)

Lewis
Lewis

Reputation: 14926

You can not return in an async function, just pass rows to a callback:

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

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

    connection.end();
};

DBmodule.getTopics(function(rows){
    console.log(rows);
});

Upvotes: 4

giwiro
giwiro

Reputation: 336

As Tresdin said a callback should be the solution. I found this ORM for Node, it works with many sql databases:

http://docs.sequelizejs.com/en/latest/

Upvotes: -1

Related Questions