sql.Connection is not a constructor [nodejs expressjs and SqlServer] --- - node.js

I am trying to write a backend API in node and express JS to connect to SQL Server[with windows authentication] and fetch data. The error message is --
const poolPromise = new sql.Connection(config)
TypeError: sql.Connection is not a constructor
The relevant config file code is dbConfig.js :
const sql = require('msnodesqlv8')
const config = {
database: 'ApiDemoDB',
server: '.\\SQLEXPRESS',
driver: 'msnodesqlv8',
options: {
trustedConnection: true
}
}
const poolPromise = new sql.Connection(config) <-------this line error
.connect()
.then(pool => {
console.log('Connected to MSSQL')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config!: ', err))
module.exports = {
sql, poolPromise
}
What is the meaning of this error message? sql.Connection is not supposed to take any parameter[config]? I don't get it, what am I supposed to do differently here? What additional code changes do I have to make in order to get this working? Can you please help me solve this problem so that the API can connect to the mssql database? As you can see, as of now I have very little code. Barebones.
Thanking you in advance.
*********************************** EDIT ***********************************
I have changed the code around quite a bit.
My dbconfig.js file is now as:
const sql = require('mssql');
const msnodesqlv8=require('msnodesqlv8');
var dbconfig = {
server: 'localhost',
database: 'ApiDemoDB',
driver: 'msnodesqlv8',
options: {
enableArithAbort:true,
trustedConnection: true,
instancename:'SQLEXPRESS'
},
port:1433
}
module.exports=dbconfig;
And then a separate dbconnect.js file as:
var sql = require("mssql/msnodesqlv8")
var dbConfig = require("./dbConfig")
var dbConnect = new sql.connect(dbConfig,
function(err)
{
if(err){
console.log("Error while connecting to database: " + err)
}else{
console.log("connected to database: " + dbConfig.server)
}
}
)
module.exports = dbConnect
Now, the error that I have is ->
Error while connecting to database: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
What does this even mean. It's pointing to the dbconfig file, but what changes to be written there, can you suggest me? Thanks

Related

mysql2 does not log the query with aws-xray-sdk and aws-xray-sdk-mysql

After following the reference links to trace mysql query
https://github.com/aws/aws-xray-sdk-node/issues/275
https://github.com/aws/aws-xray-sdk-node/issues/6
I have tried to log mysql2 logs but it does not work with aws-xray-sdk and aws-xray-sdk-node npm packages.
I know that aws-xray works well with mysql but it does not work and trace with mysql2.
Following is my code of database connection.
const mysql2 = require("mysql2");
const awsXRay = require("aws-xray-sdk");
const captureMySQL = require('aws-xray-sdk-mysql');
const mysql = captureMySQL(mysql2);
module.exports.getConnection = async (client, service) => {
const poolConfig = {
host: mysqlHost,
port: mysqlPort,
user: mysqlUser,
password: mysqlPass,
database: mysqlDb,
multipleStatements: true
};
const connection = mysql.createConnection(poolConfig);
connection.connect();
// create promise to use await
connection.query = util.promisify(connection.query);
return connection;
};
I have tried to logged the queries but it does not work anyway.
Thank you for to put some light on this issue.

Cannot connect local PostgreSQL DB in Nodejs

I connect my PostgreSQL local database in Node.js server using pg.
All worked fine, but suddenly it stopped to work.
This is my code:
const {Pool} = require('pg')
const connectionString = process.env.DATABASE_URL;
const ssl = process.env.NODE_ENV == 'production' ? '?ssl=true' : '';
const pool = new Pool({
connectionString: connectionString + ssl
});
const db = {
pool: pool,
test: async () => {
try {
console.log('before connection');
let result = await pool.query('SELECT $1::text as status', ['connected']);
console.log('connected')
return result.rows[0].status;
} catch (error) {
console.error('Unable to connect to the database:', error);
return null;
}
}
}
module.exports = db;
Here I call it:
const express = require('express')
const Router = express.Router();
const db = require('./database')
Router.get('/testdb', async (req, res) => {
try {
let result = await db.test();
res.status(200).send(result);
} catch (error) {
res.status(500).send(error);
}
})
It stuck on pool.query. 'before connection' is logged, no error is thrown.
The very same code works fine with my remote db, and I can connect the local db with pgAdmin.
This was an incompatibility issue between pg and the node.js 14 version. See also the following GitHub issues where this was tracked and fixed:
https://github.com/brianc/node-postgres/issues/2180
Pull request: https://github.com/brianc/node-postgres/pull/2171
tl;dr: Upgrade pg to a version larger than 8.0.3 (pg>=8.0.3).
I found my problem in node version - some days ago I updated it to 14.5.0.
revise it to 12.18.2 LTS solve the problem.

A way to create a mssql database if it does not exist with sequelize.sync()?

I'm trying to create a database with sequelize if one doesn't exist;
I created am initial migration with the following code.
const env = process.env.NODE_ENV || 'development';
const {database, username, password, dialect} = require(__dirname + '/../config/config.json')[env];
module.exports = {
up: (queryInterface, Sequelize) => {
const sequelize = new Sequelize("", username, password, {
dialect: dialect,
});
return sequelize.query(`CREATE DATABASE '${database}';`);
},
down: (queryInterface, Sequelize) => {
queryInterface.dropDatabase(database);
}
};
And then call it in the index.js file.
sequelize.sync({ force: true })
.then(() => {
console.log(`Database & tables created!`)
});
When I try and run it I get the following error "Unhandled rejection SequelizeAccessDeniedError: Login failed for user 'sa'."
However if I create the database using SQLPro it connects without an issue.
I could not find a way to do this via sequelize; however, I was able to resolve it using the mssql npm module. Here was my solution:
//code in my index.js for sequelize
const config = require(__dirname + '/../config/config.json')[env];
const mssql = require('mssql');
//set up connection
const pool = new mssql.ConnectionPool({
user: config.username,
password: config.password,
server: 'localhost',
});
//create database if one does not exist
pool.connect(error => {
if(error) {
console.log(error);
} else {
pool.query(`IF DB_ID('${config.database}') IS NULL CREATE DATABASE ${config.database}`);
}
});
I am still interested if you can do something similar with sequelize. If anyone has found a way using only sequelize please let me know.
Thanks!

How to connect openshift Phpmyadmin database using Nodejs Server?

How to connect "openshift phpmyadmin database" using nodejs server
Below is my code ... I am not getting result from the database ...
log :
Success{"fieldCount":0,"affectedRows":0,"insertId":0,"serverStatus":2,"warningCo
unt":0,"message":"","protocol41":true,"changedRows":0}
var connection = mysql.createConnection({
OPENSHIFT_NAMMAOORU_DB_HOST :'127.4.188.2',
OPENSHIFT_NAMMAOORU_DB_PORT :'3306',
OPENSHIFT_NAMMAOORU_DB_USERNAME:'adminfxxxxx',
OPENSHIFT_NAMMAOORU_DB_PASSWORD:'xxxxxxxxx',
OPENSHIFT_NAMMAOORU_DB_URL:'mysql://adminxxxx:xxxxxxx#127.4.188.2:3306',
//database:'nammaooru'
});
connection.connect(function(err,success){
if (err) {
throw err;
console.log("Error"+JSON.strinerr);
}
else
{
console.log("Success"+JSON.stringify(success));
}
});
app.get('/city',function(req,res){
try{
//var id = req.query.id;
/*var t=req.query.id;
console.log(t);
*/ /* var data = {
"error":1,
"Books":""
};*/
console.log(req.params.cityid);
var t=1;
connection.query("SELECT * from city",function(err, rows, fields){
console.log("success"+JSON.stringify(rows));
//console.log("success"+JSON.stringify(fields));
//console.log(JSON.stringify(rows));
res.send(JSON.stringify(err));
//console.log("success"+JSON.stringify(err));
});
}
catch(e)
{
console.log(e);
}
});
Local Rest url http://localhost:8000/city
{ code: "ER_NO_DB_ERROR", errno: 1046, sqlState: "3D000", index: 0 }
I don't think you are creating the mysql connection properly:
var connection = mysql.createConnection({
host: '127.4.188.2',
user: 'adminfxxxxx'',
password: 'xxxxxxxxx',
port: 3306
});
Try this just add database name as below
var connection = mysql.createConnection({
host :'127.4.188.2',
port :'3306', // if this doesn't work try removing port once
user:'adminfxxxxx',
password:'xxxxxxxxx',
database:'xxxxxxxxx', //specify database Name

mongodb + node connection string

I'm having trouble connecting mongodb to my local machine. I'm new at this and can't seem to figure it out from the docs or other stackoverflow posts.
I have a database.js file, and I think my connection string is wrong:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost');
// I've tried this too:
// mongoose.connect('mongodb://localhost/test');
// mongoose.connect('mongodb://localhost:8080/test');
module.exports = {
'url' : 'mongodb://localhost:27017/test'
}
I've got mongod running in one tab and shows 4 connections open - I don't know if it's this or the connection string.
Then in a 2nd tab, I've connected to a db called "test".
Lastly there's a very simple view. When I navigate to localhost:8080 (where process.env.PORT || 8080 is pointing to in server.js), it doesn't connect.
Try this
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');//Here test is my database
var Cat = mongoose.model('Cat', { name: String });
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
if (err) {
console.log(err);
} else {
console.log('meow');
}
});
Here is configuration file
{
"db": {
"connection": "mongodb://localhost",
"name": "testdb"
}
}
Here is usage in code:
var dbUrl = config.get('db:connection') + '/' + config.get('db:name');
var db = mongoose.connection;
mongoose.connect(dbUrl, function(err) {
//your stuff here
});
Hope, it helps.
P.S. Could you please provide how you catch no connection to db?

Resources