SQL Server connection with Node js - node.js

var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: '1234',
server: 'AHMAD\SQLEXPRESS',
database: 'dbms_lab4',
port:1433,
encrypt:false
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Products', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
I can't connect to SQL Server. When I run the above program and access localhost:5000, nothing appears on the browser but a message on the terminal of vscode:
"The default value for `config.options.enableArithAbort` will change from `false` to `true` in the next major version of `tedious`. Set the value to `true` or `false` explicitly to silence this message. node_modules\mssql\lib\tedious\connection-pool.js:61:23
ConnectionError: Connection is closed.
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:447:37)
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\tedious\request.js:346:11)
at Request.query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:383:12)
at Immediate.<anonymous> (D:\JS\Sql_Connection\server.js:27:17)
at processImmediate (internal/timers.js:458:21) {
code: 'ECONNCLOSED',
name: 'ConnectionError'
}
ConnectionError: Failed to connect to AHMADSQLEXPRESS:1433 - getaddrinfo ENOTFOUND AHMADSQLEXPRESS
at Connection.<anonymous> (D:\JS\Sql_Connection\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:428:26)
at Connection.emit (events.js:321:20)
at Connection.socketError (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:12)
at D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at GetAddrInfoReqWrap.callback (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connector.js:158:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:76:17) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to AHMADSQLEXPRESS:1433 - getaddrinfo ENOTFOUND AHMADSQLEXPRESS
at ConnectionError (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:56)
at D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at GetAddrInfoReqWrap.callback (D:\JS\Sql_Connection\node_modules\mssql\node_modules\tedious\lib\connector.js:158:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:76:17) {
message: 'Failed to connect to AHMADSQLEXPRESS:1433 - getaddrinfo ENOTFOUND AHMADSQLEXPRESS',
code: 'ESOCKET'
},
name: 'ConnectionError'
}
ConnectionError: Connection is closed.
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:447:37)
at Request._query (D:\JS\Sql_Connection\node_modules\mssql\lib\tedious\request.js:346:11)
at Request.query (D:\JS\Sql_Connection\node_modules\mssql\lib\base\request.js:383:12)
at D:\JS\Sql_Connection\server.js:27:17
at D:\JS\Sql_Connection\node_modules\mssql\lib\base\connection-pool.js:241:7
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
code: 'ECONNCLOSED',
name: 'ConnectionError'
}"

For SQL Connections: "Microsoft style strings of hostname\instancename are not supported."
EG from : https://www.w3schools.com/nodejs/nodejs_mysql.asp
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
You need to update your config accordingly.

try escaping the \ in the server name
Change
server: 'AHMAD\SQLEXPRESS'
To
server: 'AHMAD\\SQLEXPRESS',

Related

rror: querySrv ECONNREFUSED _mongodb._tcp.cluster0.xk55obw.mongodb.net

Im trying to connect the database in my nodejs project.
I have created a mongo account and I have chosen Coonect your application to your cluster using MonngoDB's native drivers.
So the code to connect with the database is like this:
db.js
const mongoose = require("mongoose");
const connectDB = async () => {
const conn = await mongoose
.connect(
"mongodb+srv://username:<password>#cluster0.xk55obw.mongodb.net/?retryWrites=true&w=majority",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
)
.then(() => {
console.log("Database Connected");
})
.catch((err) => console.log(err));
};
module.exports = connectDB;
When I run the project in my terminal I get this error:
Error: querySrv ECONNREFUSED _mongodb._tcp.cluster0.xk55obw.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:dns:213:19) {
errno: undefined,
code: 'ECONNREFUSED',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster0.xk55obw.mongodb.net'
}
The username and password are correct, I have checked them.
How can I solve this error?

Can't connect to the local MongoDB server running on localhost:27017 from my express application

I can't connect to the local mongodb server running on localhost:27017 from my express application. I'm pretty sure that I haven't done anything wrong in the code I wrote as I've copied it from a tutorial. The code worked fine on that tutorial. And I've also made sure that the mongodb service is running. I've already created a database called "blog" from mongosh shell and inserted some data to a collection called "authors" on it. I've also installed the MongoDB Node Driver using "npm install mongodb" command. But whenever I try to run npm start, this error shows up and I can't run my application thereafter.
E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\sdam\topology.js:306
const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
^
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\sdam\topology.js:306:38)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 195900556,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\cmap\connect.js:382:20)
at Socket.<anonymous> (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\cmap\connect.js:302:22)
at Object.onceWrapper (node:events:642:26)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
[Symbol(errorLabels)]: Set(0) {}
}
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.2.0
[nodemon] app crashed - waiting for file changes before starting...
This is the code I wrote on database.js to create the connection to the local mongodb server.
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
let database;
async function connect() {
const client = await MongoClient.connect("mongodb://localhost:27017");
database = client.db("blog");
}
function getDb() {
if (!database) {
throw { message: "Database connection not established!" };
}
return database;
}
module.exports = {
connectToDatabase: connect,
getDb: getDb,
};
This is the code I wrote on app.js to connect the database to it and run the application.
const path = require("path");
const express = require("express");
const blogRoutes = require("./routes/blog");
const db = require("./data/database");
const app = express();
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(blogRoutes);
app.use(function (error, req, res, next) {
console.log(error);
res.status(500).render("500");
});
db.connectToDatabase().then(function () {
app.listen(3000);
});
Your connect() function is not returning a Promise.
Try to change your code like this:
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const client = new MongoClient('mongodb://localhost:27017');
let database;
async function connect() {
try {
await client.connect();
database = client.db('blog');
console.log('MongoDB connected...');
} catch (err) {
console.log('Error connecting to database...');
process.exit(1);
}
}
In your app.js  just call the connectToDatabase function:
db.connectToDatabase();
app.listen(3000);

Issue on connecting to MongoDB Atlas via Mongoose on the node.js

I have created the cluster on the MongoDB Atlas and now trying to create the db connect to it using the connection string provided on the Atlas.
My Connection String on key.js file:
module.exports = {
//mongoURI: "mongodb://DEVELOPER:DEV1234#devconnector"
mongoURI:
"mongodb+srv://USERNAME:PWD#devconnector-7dd46.mongodb.net/test?retryWrites=true"
};
Server.js file, DB Connect:
const db = require("./config/keys").mongoURI;
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("MongoDBConnected"))
.catch(err => console.log(err));
Error message:
{ Error: querySrv ESERVFAIL
_mongodb._tcp.devconnector-7dd46.mongodb.net
at errnoException (dns.js:55:10)
at QueryReqWrap.onresolve [as oncomplete] (dns.js:243:19) code: 'ESERVFAIL', errno: 'ESERVFAIL', syscall: 'querySrv', hostname:
'_mongodb._tcp.devconnector-7dd46.mongodb.net' }
Just to add, I am getting the same error message while on trying to connect with Atlas from the Compass. Any help would be appreciated!

Mongo db Atlas 3.6.5 authentication failed

I am pretty new to node.js,am trying to write data to a free online mongo db atlas using mongoose,however i keep getting Authentication failed despite editing mongo db settings to connect from anywhere and also using correct username and password for the db user.
Here is my app.js file where i connect to mongo db
app.js:
const express = require('express');
const morgan = require('morgan');
const bodyParser= require('body-parser');
const mongoose = require('mongoose');
const app = express();
const productRoutes= require('./api/routes/products');
const ordersRoutes= require('./api/routes/orders');
mongoose.connect('mongodb+srv://hilary:'+process.env.MONGO_ATLAS_PW+'#node-rest-dnqwa.mongodb.net/test?retryWrites=true').catch(err => console.log(err));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use((req,res,next) =>{
res.header("Access-Control-Allow-Origin","*");
res.header('Access-Control-Allow-Headers','Origin,X-Requested-With,Content-Type,Accept,Authorization');
if(req.method === 'OPTIONS'){
res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,PATCH');
return res.status(200).json({});
}
next();
});
app.use('/products',productRoutes);
app.use('/orders',ordersRoutes);
app.use((req,res,next) => {
const error= new Error('not found');
error.status = 404;
next(error);
});
app.use((error,req,res,next) =>{
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
})
})
module.exports = app;
i get this error in my terminal:
{ MongoError: authentication fail
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\topologies\replset.js:1430:15
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:877:7
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:853:20
at finish (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\auth\scram.js:174:16)
at handleEnd (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\auth\scram.js:184:7)
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\auth\scram.js:289:15
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:544:18
at process._tickCallback (internal/process/next_tick.js:112:11)
name: 'MongoError',
message: 'authentication fail',
errors:
[ { name: 'node-rest-shard-00-00-dnqwa.mongodb.net:27017',
err: [MongoError] },
{ name: 'node-rest-shard-00-02-dnqwa.mongodb.net:27017',
err: [MongoError] } ] }
I am certain am using correct name and password so why cant it authenticate me,server runs on my localhost
EDIT
So i followed link to docs and now connect this way:
mongoose.connect('mongodb://hilary:'+process.env.MONGO_ATLAS_PW+'#localhost:27017/test').catch(err => console.log(err));
I then get this error in terminal:
{ MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\topologies\server.js:505:11)
at Pool.emit (events.js:180:13)
at Connection.<anonymous> (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:329:12)
at Object.onceWrapper (events.js:272:13)
at Connection.emit (events.js:180:13)
at Socket.<anonymous> (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\connection.js:245:50)
at Object.onceWrapper (events.js:272:13)
at Socket.emit (events.js:180:13)
at emitErrorNT (internal/streams/destroy.js:64:8)
at process._tickCallback (internal/process/next_tick.js:114:19)
name: 'MongoNetworkError',
message: 'failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]' }
What worked was a slight variation from the mongoose docs,it was suggested on the Atlas server,for everyone who has Mongodb 3.4+ connect using the regular mongo db driver even when using mongoose, my connection string looks like:
mongoose.connect('mongodb+srv://hilary:<password>#node-rest-dnqwa.mongodb.net').catch(err => console.log(err));

Connect multiple mongodbs, running on different aws servers

I am new to nodejs and I am facing an issue when I try to connect multiple mongodbs, running on different aws servers.
I have used tunnel-ssh but it shows failed to connect.
Can anyone provide me some information on how to connect multiple mongodbs, running on different aws servers within a single nodejs application?
const fs=require('fs')
var mongoose = require('mongoose');
var tunnel = require('tunnel-ssh');
var config = {
username:'ubuntu',
host:'my.ip.address',
agent : process.env.SSH_AUTH_SOCK,
privateKey:require('fs').readFileSync('C:\Users\\Ronit\\Downloads\\my.ppk'),
port:19735,
dstHost:'Database server Ip address',
dstPort:19735,
localHost:'127.0.0.1',
//password:'mypassword',
localPort: 19735,
keepAlive:true
};
var server = tunnel(config, function (error, server) {
if(error){
console.log("SSH connection error: " + error);
}
mongoose.connect('mongodb://localhost:19735/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'DB connection error:'));
db.once('open', function() {
// we're connected!
console.log("DB connection successful");
});
});
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED my_ip:19735
at Object.exports._errnoException (util.js:873:11)
at exports._exceptionWithHostPort (util.js:896:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1077:14)

Resources