0

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?

4
  • What is inside of userModels? Commented Jul 19, 2017 at 7:34
  • @LEQADA sorry that was a mistake in userModule.js in fact that is userModel.js I edit the code Commented Jul 19, 2017 at 7:37
  • Looks like there is still a mistake. Filename is userModel, but you import userModels Commented Jul 19, 2017 at 7:39
  • @LEQADA yes that was a mistake again, I correct the code Commented Jul 19, 2017 at 7:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, That worked correctly and sorry for my question, I start learning from Sunday and my mistakes are stupid. Thanks for your help
You are welcome, I hope you will get a better understanding of javascript and learn new things. I'm glad that this code works for you :) Good Luck!

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.