Masoud Tavakkoli
Masoud Tavakkoli

Reputation: 1020

return mysql data from module to app.js using nodejs

I am newbie in node.js and I'm sorry for my silly question.

I want to separate and organize my app for easy working with files. For this reason I create a module to do my mysql database there but I have problem with module.I can't return module data to use in my main js file app.js

console shows undefined and browser shows nothing

here is my code

App.js

var express = require('express'),
    mysql = require('mysql'),
    bodyParser = require('body-parser');

var app = express();
// app.set('view engine', 'jade');

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: 'database'
});
var port = process.env.PORT || 8080;
var User = require('./models/userModels');
var bookRouter = express.Router();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

bookRouter.route('/books')
        .post(function (req, res) {
            // console.log(book);
            // res.send(book);
        })
        .get(function (req, res) {
            res.send(User.allUsers); // <--- shows nothing
            console.log(User.allUsers); //<--- returned undefined
        });

app.use('/api', bookRouter);

app.get('/', function (req, res) {
    res.send('welcome to my API');
});

app.listen(port, function () {
    console.log('Running on PORT via gulp  ' + port);
});

userModels.js

var mysql = require('mysql');

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "luxa"
});

module.exports = {
    allUsers: con.connect(function (err) {
        if (err) throw err;
        con.query("SELECT * FROM users", function (err, result, fields) {
            if (err) throw err;
            // console.log(result); // return result correctly
            // return result; 
            callback(err, result); // Error
        });
    }),
};

what's my problem?

Upvotes: 0

Views: 262

Answers (1)

codtex
codtex

Reputation: 6558

Okay I see a lot of wrong code here. Let's have a look on this part:

allUsers:   con.connect(function(err) {
    if (err) throw err;
        con.query("SELECT * FROM users", function (err, result, fields) {
            if (err) throw err;
            // console.log(result); // return result correctly
            // return result; 
            callback(err , result); // Error
        });
    }) ...

First I can say that this is not a correct function declaration. And also I see that finally you are calling callback(err , result); but callback is coming from nowhere ... So the previous code could look like this:

allUsers: function (callback) {
    con.connect(function (err1) {
        if (err1){
            /* use return to prevent the code to continue */
            return callback(err1, null);
        }
        con.query("SELECT * FROM users", function (err2, result, fields) {
            if (err2){
                return callback(err2, null);
            }
            callback(err2, result); 
        });
    });
} 

Now lets have a look on this part of your code:

.get(function (req , res) {
    res.send(User.allUsers); // <--- shows nothing
    console.log(User.allUsers); //<--- returned undefined
})  

Basically when doing User.allUsers you are doing nothing but passing the function itself. If you want to call function use (), so User.allUsers() is the right code, but this code is asynchronous and you will get nothing again ... Now comes the part to use the callback. So previous code can look like this:

.get(function (req, res) {
    /* the code is async so first obtain the data then use res.send() */
    User.allUsers(function (err, results) {
        res.send({
            error: err, /* here you should have any error if it happens */
            results: results /* here you should have your results */
        });
    });
})

Check and see if the code is clear to you. Let me know if you have any questions.

Upvotes: 1

Related Questions