TypeError: sqlDb.Connection is not a constructor in Rest Service using Node.js
Following this correct answer, I just had this issue now when upgrading node.js modules, but having to support the older code as well, I had to write a method that can wrong seamlessly in both cases:
function CreateDbConnection(callback) {
let connectionFunc = null;
if (sql.ConnectionPool)
connectionFunc = sql.ConnectionPool;
else
connectionFunc = sql.Connection;
let connection = new connectionFunc(settings.sqlConfig, function (err) {
if (err) {
logger.error('Error connecting to database: ' + (err.message || err));
callback("ERROR", null);
} else {
callback(null, connection);
}
});
}
This will check what method is available and use it.
Example for actual usage:
CreateDbConnection(function (err, connection) {
if (err) {
console.log('connection failed');
} else {
console.log('Doing stuff with connection...');
//important to close when done:
connection.close();
}
});
Change Connection
to ConnectionPool
const conn = new sqlDb.ConnectionPool(settings.dbConfig);
conn.connect();
From the mssql package's npm documentation:
3.x to 4.x changes -
Connection
was renamed toConnectionPool
.
https://www.npmjs.com/package/mssql#3x-to-4x-changes