Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing database connections in Node.js, best practices?

I'm building an Node application which will query simple and more complex (multiple joins) queries. I'm looking for suggestions on how I should manage the mySQL connections.

I have the following elements:

  • server.js : Express
  • router1.js (fictive name) : Express Router middleware
  • router2.js (fictive name) : Express Router middleware

    //this is router1

    router.get('/', function (req, res){

    connection.connect(function(Err){...});

      connection.query('SELECT* FROM table WHERE id = "blah"', function(err,results,fields){
        console.log(results);
      });
      ...
    connection.end();
    })

Should I connect to mysql everytime '/router1/' is requested, like in this example, or it's better to leave one connection open one at start up? As:

connection.connect();
outside of:
router.get('/',function(req,res){
...
});
?
like image 450
0cnLaroche Avatar asked Mar 14 '18 19:03

0cnLaroche


People also ask

What is the best practice for opening a DB connection?

The best practice for database connections is the same regardless of the language used. You have a pool of open connections at the start of your application. You take a connection from the pool as late as possible. Return it to the pool as soon as possible.

Can we connect multiple database in node JS?

To use multiple database in a single Node. js project with Mongoose, we can use the connection's model method. const conn = mongoose. createConnection('mongodb://localhost/testA'); const conn2 = mongoose.


1 Answers

I am using mysql2 for this, it is basicly mysql but with promises. If you use mysql you can also do this.

Create a seperate file called connection.js or something.

const mysql = require('mysql2');

const connection = mysql.createPool({
    host: "localhost",
    user: "",
    password: "",
    database: ""
    // here you can set connection limits and so on
});

module.exports = connection;

Then it is probaly better you create some models and call these from within your controllers, within your router.get('/', (req, res) => {here});

A model would look like this:

const connection = require('../util/connection');

async function getAll() {
    const sql = "SELECT * FROM tableName";
    const [rows] = await connection.promise().query(sql);
    return rows;
} 
exports.getAll = getAll;

You can do this with or without promises, it doesn't matter. Your connection to the pool is automatically released when the query is finished. Then you should call getAll from your router or app.

I hope this helped, sorry if not.

like image 68
Laurent Dhont Avatar answered Oct 21 '22 10:10

Laurent Dhont