Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs- TypeError: connection.connect is not a function

Tags:

node.js

mysql

I have an app developed using ExpressJS (Express 4) framework. I am planning to use connection pooling instead of single connection, heard it allows us to reuse existing database connections instead of opening a new connection for every request to the Node application.

So in the existing code, I made a change. Replaced mysql.createConnection with mysql.createPool in the following code Note: This is just a portion of the app where the database connection is getting established.

  var mysql = require('mysql'),
    connection = mysql.createPool({
      host: 'localhost',
      user: 'root',
      password: '',
      database: 'test_db',
      port: 3306
    });
  connection.connect(function (err) {
    if (err) {
      console.log(err);
    }
  });

But when I run the app, I got the following error.

TypeError: connection.connect is not a function

Can anyone tell me how to resolve this error? Thanks!

Package.json file

{
  "name": "testapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "hola"
  },
  "author": "user",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "cake-hash": "0.0.6",
    "compression": "^1.7.1",
    "cors": "^2.8.4",
    "express": "^4.16.2",
    "https": "^1.0.0",
    "moment": "^2.19.2",
    "morgan": "^1.9.0",
    "mysql": "^2.15.0"
  }
}
like image 563
Lonewolf Avatar asked Jan 25 '18 05:01

Lonewolf


1 Answers

Looks like with pools you want to .getConnection() and not .connect().

From mysql package documentation:

var mysql = require('mysql');
var pool  = mysql.createPool({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret',
  database : 'my_db'
});

pool.getConnection(function(err, connection) {
  // connected! (unless `err` is set)
});
like image 62
Brett Fuller Avatar answered Nov 07 '22 09:11

Brett Fuller