1

I'm newbie in node.js I wrote a userModel module to do database stuff using MySQL and works fine but just for first time. When I refresh the page mysql data returns null

userModel.js // my module

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

module.exports = {
    allUsers: function (callback) {
        con.connect(function (err1) {
            if (err1){
                return callback(err1, null);
            }
            con.query("SELECT * FROM users", function (err2, result, fields) {
                if (err2){
                    return callback(err2, null);
                }
                callback(err2, result);
            });
        });
    }
};

app.js // main js file

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

var app = express();
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')

    .get(function (req, res) {

        User.allUsers(function (err, results) {

        var id = req.query.id;

        var somre = _.find(results , function (param) { //result is null in second refresh
            return param['id'] == id;
        });

        console.log(results);
        res.send(somre);
        });
    })

app.use('/api' , bookRouter)


app.get('/' , function (req , res) {
    res.send('welcome to my API');
});
3
  • Can you try console logging the err variable to see if you get anything there? Seems like something went wrong. Commented Jul 19, 2017 at 13:05
  • Right... look at the two invocations of callback. One of them literally passes null for results. It's when there is an error. Try inspecting the error with console.log. Commented Jul 19, 2017 at 13:07
  • @Brandon yes I have this error Error: Cannot enqueue Handshake after already enqueuing a Handshake. Commented Jul 19, 2017 at 13:14

1 Answer 1

3

You are not releasing the mySQL connection after querying it. Hence, You are calling the connect() more than once, when there is already another connection active the second time.

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

1 Comment

@Brandon Absolutely, Any production SQL DB should use connection pooling..

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.