0

I'm wondering how to use the module node-mysql correctly in Node.js (using Express.js). I have a main router with this:

var Post = require('./models/post.js');    

app.get('/archives', function (req, res) {
    Post.findArchives(function(posts, err) {
        if(err)
            res.send('404 Not found', 404);
        else
            res.render('archives', { posts: posts});
    });
});

And here's the content of the file post.js:

var mysql = require('mysql');
var dbURL = 'mysql://root@localhost/mydatabase';

exports.findArchives = function(callback) {
    var connection = mysql.createConnection(dbURL);
    connection.query('SELECT * FROM blog_posts_view WHERE status != 0 ORDER BY date DESC', function(err, rows) {
        if(err) throw err
        callback(rows, err);
        connection.end();
    });
};

How can I improve it? Improve the error handling? Also, there's the function handleDisconnect(connection); on their Github (https://github.com/felixge/node-mysql) that I'm not really sure how to integrate to make sure that the application will not crash when the database is not responding.

Thanks!

1 Answer 1

1

Take a look at the mysql-simple library. It combines node-mysql with a pooling library to create a connection pool, and also includes the code to handle the disconnects.

If you want to make it super easy, you could just use that module.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.