Node.js "Error: read ECONNRESET" - node.js

I am trying to connect to mongo via Node.js and I'm getting the following error:
connection error: { Error: read ECONNRESET
at exports._errnoException (util.js:1022:11)
at TCP.onread (net.js:610:25) name: 'MongoError', message: 'read ECONNRESET' }
(node:3868) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: read ECONNRESET
Here is the code I'm using to connect:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
module.exports = (config) => {
const fs = require('fs');
let key = fs.readFileSync('../server/test/keys/cert_key.pem');
let ca = [fs.readFileSync('../server/test/keys/ca.pem')];
let o = {
server: {
sslValidate: true,
sslCA: ca,
sslKey: key,
sslCert: key
}
};
mongoose.connect(config.connectionString, o);
let database = mongoose.connection;
database.on('error', console.error.bind(console, 'connection error:'))
database.once('open', (error) => {
if (error) {
console.log(error);
return;
}
console.log('MongoDB ready!')
});
require('./../models/Role').initialize();
require('./../models/User');
require('./../models/Item');
require('./../models/character/Character_item');
require('./../models/Article');
require('./../models/Friend_request');
require('./../models/Code');
require('./../models/Ring');
require('./../models/Ring_shop');
require('./../models/Comment');
};
If I try to connect to mongo from Robo3T, it works. So it seems the problem is in my Node code. Any suggestions?

Accordin mongoDB node driver documentation you must pass ssl: true in the server option in order to connect via SSL otherwise SSL is ignored.
My standard ssl db options is the following :
server: {
ssl: true,
sslValidate:true,
sslCA: ca,
ca: ca,
sslKey: key,
sslCert: key
}

I was having the same issue as I was working on the cloud provided by MongoDB. The reason it was happening with me was that I have configured my home IP to be connected and not my work IP. After adding my work IP in the cloud settings I was able to connect

Confirm that your mongodb database's file is not damaged。If .wt file has damaged, you'll got that error. The .wt filen in your storage path. eg:
storage:
dbPath: E:\Data\mongodb
You can use mongorestore command to repair data if you backuped before. otherwise you can drop the database and re-init a new one.

Related

SSL Routines error when connecting to local DB

So I have this piece of code that is responsible for checking if a connection is valid:
const sequelize = new Sequelize(req.body.database, req.body.user, req.body.password, {
host: req.body.host,
dialect: 'mssql',
port: req.body.port,
dialectOptions: {
options: {
encrypt: true,
}
}
});
sequelize.authenticate().then((err) => {
res.send('Connected');
})
.catch((err) => {
console.log(err.message)
res.send(err.message);
});
This worked perfectly when I was connecting to a local DB on my network. However, when I was trying to connect to a DB through a VPN (simulating a local network) I got the following error:
Failed to connect to 10.1.90.20:1433 - 4C300000:error:0A000102:SSL
routines:ssl_choose_client_version:unsupported
protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1983:
I read somewhere that adding
cryptoCredentialsDetails: {
minVersion: 'TLSv1'
}
in the options will resolve this but it just gave me a new error:
Failed to connect to 10.1.90.20:1433 - 70290000:error:0A0C0103:SSL
routines:tls_process_key_exchange:internal
error:c:\ws\deps\openssl\openssl\ssl\statem\statem_clnt.c:2255:
Any idea how to fix this?
Keep in mind that both Databases are local however one of them is on a remote network accessible through SSL VPN.

Connecting to PostgresSQL hosted online using NodeJS

I'm currently trying to create a functional query from the database to post it into a created a csv file, however I am unable to connect to the PSQL host programmatically. So what I am trying to do is :-
Connect to DB and query results
Push results to an Excel File
Continue()
SFTP Results to myself on SFTP Server and place file in directory.
I am able to connect to the PostgresDB manually by the following in CLI:-
ssh username#xx.xx.xx.xx //Doesnt need password because my id_rsa key is stored on the Server
psql -U username -h LOCALHOST -p 5432 -d databasename pass- password (Manually input)
Furthermore, connecting through Visual Studio Code works as well however I need to connect to the server (Remote Connection) and then connect to the Database using a postgres Driver.
After investigating it, I figured I firstly need to connect using SSH to the server, then and only then I will be allowed to access the Database.
This is how I approached it through Code :-
Index.js
const serverConnectionParams = require('./src/config/serverConn');
function testConnectionServer() {
try {
serverConnectionParams.connectToServer();
} catch (err) {
console.error(err);
}
}
testConnectionServer();
serverConn.js
const { Client } = require('ssh2');
const { readFileSync } = require('fs');
const databaseConnectionParams = require('./databaseConn');
function connectToServer() {
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.exec('uptime', (err, stream) => {
if (err) throw err;
databaseConnectionParams.auth(); *// This is the database connection param*
stream.on('data', (data) => {
console.log('STDOUT: ' + data);
}).stderr.on('data', (data) => {
console.log('STDERR: ' + data);
});
});
}).connect({
host: 'xx.xx.xx.xx',
username: 'username',
privateKey: readFileSync('src/key/id_rsa')
});
}
exports.connectToServer = connectToServer;
databaseConn.js
const { readFileSync } = require('fs');
const envParam = require('./env.js');
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize(envParam.database, envParam.username, envParam.password, {
host: envParam.host,
dialect: envParam.dialect,
ssl: true,
pool: {
max: envParam.pool.max,
min: envParam.pool.min,
acquire: envParam.pool.aquire,
idle: envParam.pool.idle
}
});
async function auth() {
try {
console.log('trying to connect')
sequelize.validate();
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
exports.auth = auth;
env.js
const env = {
database: 'databasename',
username: 'username',
password: 'password',
host: 'ip#',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
aquire: 30000,
idle: 10000
}
};
module.exports = env;
After running my node index.js I receive the following error statement :-
Client :: ready
trying to connect
STDOUT: 10:43:09 up 1:21, 1 user, load average: 5.71, 6.03, 5.15
C:\Users\~\node_modules\sequelize\lib\dialects\postgres\connection-manager.js:184
reject(new sequelizeErrors.ConnectionError(err));
^
ConnectionError [SequelizeConnectionError]: no pg_hba.conf entry for host "xx.xx.xx.xx", user "username", database "databasename", SSL off
at Client._connectionCallback
{
parent: error: no pg_hba.conf entry for host "xx.xx.xx.xx", user "username", database "databasename", SSL off
at Parser.parseErrorMessage
{
length: 154,
severity: 'FATAL',
code: '28000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'auth.c',
line: '490',
routine: 'ClientAuthentication'
},
original: error: no pg_hba.conf entry for host "x.x.x.x", user "username", database "password", SSL off
at Parser.parseErrorMessage (C:\Users\~\node_modules\pg-protocol\dist\parser.js:287:98)
at Parser.handlePacket (C:\Users\~\node_modules\pg-protocol\dist\parser.js:126:29)
at Parser.parse (C:\Users\~\node_modules\pg-protocol\dist\parser.js:39:38)
at Socket.<anonymous> (C:\Users\~\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:394:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:199:23) {
length: 154,
severity: 'FATAL',
code: '28000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'auth.c',
line: '490',
routine: 'ClientAuthentication'
}
}
Investigating the Error Code: 28000
Found this link explaining the issue as an authentication attempt failure
https://help.heroku.com/DR0TTWWD/seeing-fatal-no-pg_hba-conf-entry-errors-in-postgres
Also found several solutions online regarding pg_hba.conf needs to use md5 and then restart postgress (Not tried, as i cannot restart the postgress service)
error: Ident authentication failed for user
Found another solution explaining it was an SSL issue (Tried it and it didnt work)
Node.js, PostgreSQL error: no pg_hba.conf entry for host
After using SSL it would change the error code to the following :-
SequelizeConnectionError: self signed certificate
Found a solution to that here:-
SequelizeConnectionError: self signed certificate
After I put that it would give me a different error that rejectUnauthorized is depreciated and very old version (Cant seem to reproduce the error code as of the moment)
So my hands are tied at the moment, any help will be great!
I've also tried using different Javascript modules instead of sequelize however they all have the same authentication issue.
I also tried to pass my id_rsa key, however it wouldnt solve my issue at all.
My assumptions are even though I am passing the connToDatabase function inside the SSH connection, it is still searching for the ip# in the incorrect location. (Ip# of DB on the server is 192.168.31.4)
But when using that IP# it will say ERR Connection Timed out
Another Assumption I have is that the Database has many restrictions from connecting and require further more params.
UPDATE:
I tried editting the pg_hba.conf file through remote access on VSC however it would give me error cannot read file.
Any help would be great!
I had completely forgotten that I posted this question.
The solution to it was pretty straight forward, after investigating it for a while I realized I was making a mistake in connection params.
For others who require help with such issues I will post the solution in a simple manner.
Basically, I needed first to SSH to the server and add a tunnel to my connection to connect to the database. Then and only then will my sequelize params for the database pass through because I have completely connected to the server and internal postgresql database.
So TLDR
SSH -> Tunnel -> Sequelize
ssh(10.x.x.1, etc) -> addTunnel(localhost, etc) -> sequelize(databaseName, etc)
EDIT: Added Code for reference
const Ssh2Promise = require('ssh2-promise');
const { readFileSync } = require('fs');
async function connectToServer(callback) {
const ssh = new Ssh2Promise({
host: '10.x.x.1',
username: 'usernameofssh',
privateKey: readFileSync('src/key/id_rsa'), //This is only for RSA Fingerprint, if you do not have said fingerprint you can use "passphrase" with your password instead
});
const tunnel = await ssh.addTunnel({
remoteAddr: '192.168.0.1', //This is the database connection ip#, once connected to it you can fetch from LOCALHOST. Incase its AWS it would be test.test-test.amazonaws.com
remotePort: 1234, //Port for connection
localPort: 1234,
});
//Don't forget to throw it in a try catch for feedback
await auth(callback); //Send it wherever you need it to go
}

MongooseError: Operation users.insertOne() buffering timed out after 10000ms” in Mongo Db atlas

I am currently working with node and mongoDB
here is my code
import dotenv from "dotenv";
import mongoose from "mongoose";
dotenv.config();
mongoose
.connect(
`mongodb+srv://OmniBotBuilder:${process.env.DBPASS}${process.env.DBUSER}.kx2vg.mongodb.net/${process.env.DBNAME}?retryWrites=true&w=majority`,
{
useUnifiedTopology: true,
useNewUrlParser: true,
}
)
.catch(() => console.error("Unable to connect to DB"));
mongoose.connection.on("connected", () => {});
const Schema = mongoose.Schema;
const omniGamesSchema = new Schema({
discordId: Number,
steamId: Number,
});
const omniGamesModel = mongoose.model("omniGamesSchema", omniGamesSchema);
const createNewUser = (discordId, steamId) => {
const newUserMap = new omniGamesModel({
discordId: discordId,
steamId: steamId,
});
newUserMap.save((err) => {
if (err) {
console.error(err);
}
});
};
export { createNewUser };
and the error i am getting is this one
MongooseError: Operation omnigamesschemas.insertOne() buffering timed out after 10000ms
at Timeout. (C:\Users\dahiy\OneDrive\Desktop\bots\omni-games\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:198:23)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
This issue normally is caused because:
wrong auth, by the meaning the mongo path string is wrong so maybe double check your pass and username
check the allowed IP to access the database from the mongo website, if you want it to be accessed from everywhere just use IP: 0.0.0.0/0
Your internet connection might be slow to the point it cannot connect to the DB
Hope you found this helpful! :)
You can open https://cloud.mongodb.com/
Click connect Goto the Connect your application
Select Driver Node.js version 4.1 leter
Copy the link which you have to show than paste this link to your
project .env file now try to run application connect Database and
check.

Failed to connect node.js app to MongoDB Atlas despite using the correct connection credentials

I'm trying to connect my node.js application to MongoDB Atlas but I keep getting a "Bad authentication error" and yes, I am using the current database user credentials.
Here is the snippet that's supposed to connect to MongoDB Atlas
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
console.log('MongoDB Connected: ' +conn.Connection.host)
}catch (err) {
console.error(err)
process.exit(1)
}
}
My terminate shows me bad authentication and some key-pairs that look so:
{
ok: 0,
code: 8000,
codeName: 'AtlasError',
name: 'MongoError'
}
Any ideas why it is not connecting to MongoDB Atlas?
I finally singled out the problem, it was the MongoDB connection string. I was simply inserting my password in the password field without removing the angle brackets.

Trouble Connecting to compose.io mongodb instance with mongoose

I am using these instructions:
https://help.compose.com/docs/connecting-to-mongodb#mongoose-node-and-compose
This is the connection string they gave me:
MONGO_URI=mongodb://*****:******#aws-us-west-2-portal.1.dblayer.com:15782,aws-us-west-2-portal.0.dblayer.com:15782/mydbname?ssl=true
This is the code I am trying:
certFileBuff = [fs.readFileSync(MONGO_CERT_PATH)]
options = {
mongos: true,
sslCA: certFileBuff,
sslValidate: false,
ssl: true
}
mongoose.connect(MONGO_URI, options)
At this point I get Authentication Failure errors:
if i remove ?ssl=true from the connection string I get the error:
no mongos proxy available
Does anyone have mongoose working with compose.io recently?
If you are not using sharding in mongo set mongos to false.
You can read about sharding in mongo here https://docs.mongodb.com/manual/core/sharded-cluster-query-router/
As it turns out. I had a password that didn't get along with the connection string. I changed the password to something shorter and it worked. fwiw the password that didn't work was: tapasleechframegoldrabbitsauceb88 (Obviously I'm not using anymore)
What I learned:
If you get a mongos proxy error its probably bad config. Make sure ssl=true is set on the connection string and ssl: true in your config.
If you get code: 18 authentication error then the password is either wrong or not formatted properly.
Here is my final working code:
const MONGO_URI = mongodb://****:*****#aws-us-west-2-portal.1.dblayer.com:15782,aws-us-west-2-portal.0.dblayer.com:15782/dbName?ssl=true
let ca, options = {}
if(MONGO_CERT_PATH) {
try {
ca = fs.readFileSync(encodeURI(MONGO_CERT_PATH))
options = {
mongos: {
ssl: true,
sslValidate: true,
sslCA: [ ca ]
}
}
} catch(err) {
logger.warn('mongo ssl cert missing')
}
}
let db = mongoose.connection
db.on('error', (e) => logger.error('connection error:', e))
db.once('open', () => {
logger.info('db connected')
})
mongoose.connect(MONGO_URI, options)

Resources