0

I am new to pooling in node js. I am trying to start a pool connection at crud_new_op.js file and export the connection to db_crud.js and log it in the console.

I tried different ways but i always get "undefined" for the connection that i export from the pool...

db_crud.js

var express = require('express');
var app = express();

var crud = require('./routes/crud_op_new.js');

app.get('/search',(req,res)=>{
console.log(crud.connection);
});

app.listen(8044);

crud_op_new.js

var mysql = require('mysql');

var conn = require('../config/db_config.js');

var db = conn.database;

var pool = mysql.createPool({
 connectionLimit : 100,
 host : db.host,
 user : db.user,
 password : db.password,
 database : db.database
});

pool.getConnection(function(err,connection){
 if(!err){
    exports.connection;
 }
 else {
    console.log("Error at pool creation");
 }
});

There i nothing wrong with database connection.

2 Answers 2

2

Why don't you just pass forward the pool.getConnection function?

// crud_op_new.js
exports.connection = pool.getConnection.bind(pool);

// db_crud.js
crud.connection(function (err, con) {
    if (err) throw err;
    console.log(con);
});
Sign up to request clarification or add additional context in comments.

1 Comment

This should be the simplest way without passing any callback.
0

You should return the connection

db_crud.js

var express = require('express');
var app = express();
var crud = require('./routes/crud_op_new.js');

app.get('/search',(req,res)=>{
 crud.connection(function (con) {
    console.log(con);
 });
});

app.listen(8044);

crud_op_new.js

var mysql = require('mysql');

var conn = require('../config/db_config.js');

var db = conn.database;

var pool = mysql.createPool({
 connectionLimit : 100,
 host : db.host,
 user : db.user,
 password : db.password,
 database : db.database
});

exports.connection = function (callback) {
  pool.getConnection(function(err,con){
    if(err) throw err;
    return callback(con);
  });
}

13 Comments

exports.connection() will still return undefined
Nope. I have tried that. It will show connection object.
I am too getting same undefined
@digit, there is no return statement in your function which means i'll return undefined
Oh. I just notice that you don't initiate connection. Where do you call create pool in db_crud.js
|

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.