MongoDB Atlas - How to fix 'TransientTransactionError' on shared web-hosting - node.js

TransientTransactionError when attempting to connect from shared web-host to Mongo Atlas
I actually had this working at one point but I had to wipe and restart my project from scratch on my web host. Now seemingly out of nowhere I keep getting the above-mentioned error when trying to connect to Atlas. I have already tried whitelisting IP addresses including both my server IP as well as 0.0.0.0/0 (the 'allow all' wildcard) in Atlas.
I have also tried using the 'full driver' snippet instead of mongoose but still receive the same error. Lastly, I want to point out that the exact same code works just fine on my local machine.
Here's my function:
const mongoose = require("mongoose");
const config = require("./config");
module.exports = cb => {
if (mongoose.connection.readyState < 1) {
mongoose.connect(config.db).then(
() => {
console.log("Database linking successful!");
return cb ? cb : null;
},
err => {
console.log("Failed to connect to database.", err);
}
);
}
};
Here's what the error message looks like:
{ MongoNetworkError: failed to connect to server [<mongodb-shard-goes-here>.mongodb.net:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 54.145.177.180:27017]
at Pool.<anonymous> (/home/titanesp/public_html/server/node_modules/mongodb-core/lib/topologies/server.js:431:11)
at Pool.emit (events.js:182:13)
at connect (/home/titanesp/public_html/server/node_modules/mongodb-core/lib/connection/pool.js:557:14)
at makeConnection (/home/titanesp/public_html/server/node_modules/mongodb-core/lib/connection/connect.js:39:11)
at callback (/home/titanesp/public_html/server/node_modules/mongodb-core/lib/connection/connect.js:261:5)
at TLSSocket.err (/home/titanesp/public_html/server/node_modules/mongodb-core/lib/connection/connect.js:286:7)
at Object.onceWrapper (events.js:273:13)
at TLSSocket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }

Related

How to Use Node SMPP to Connect to InetLab SMPP Server

I am trying to build an SMS an SMS Client using NodeJS which should connect to ``Inetlab ```` SMPP Server to send Short messages. I downloaded Inetlab SMPP client and Server and run them both. When I try to connect and send an SMS from the client via port 7777 (Not that it matters), The connection is bound successfully and the message is sent across.
My problem is when I try connect to the same local SMPP server via a client that I have bult with NodeJS using the node-smpp library, the connection fails even though I am using the same localhost and port 7777.
Below is my connection code:
module.exports = class{
constructor(){
this.session = null
this.smppConfig = {
url:"smpp://localhost:7777",
auto_enquire_link_period:10000,
debug:true
}
}
StartSmppSession= ()=>{
return new Promise( async(resolve, reject)=>{
try{
console.log(this.smppConfig)
this.session = smpp.connect(this.smppConfig,()=>{
this.session.bind_transceiver({
system_id:process.env.SMPP_SYSTEM_ID,
password:process.env.SMPP_PASSWORD
},(pdu)=>{
if(pdu.command_status === 0){
resolve({message:"Connection bound successfully!"})
}else{
reject({message:"Failed to bind!",pdu})
}
})
})
}catch(err){
//reject(err.message)
}
})
}
sendSMS = (payload)=>{
return new Promise(async (resolve, reject)=>{
try{
//payload = {destination_addr:"phone_number", "short_message":"The message here"}
this.session.submit_sm(payload, async (pdu)=>{
pdu.command_status === 0 ? resolve("Message successfully sent!") : reject("Failed to send SMS!")
})
}catch(err){
reject(err.message)
}
})
}
}
When I invoke the StartSmppSession() function in my controller, I get the following error log:
2022-12-06T09:30:40.973Z - cli - 315644 - socket.error - connect ECONNREFUSED ::1:7777 - {"errno":-4078,"code":"ECONNREFUSED","syscall":"connect","address":"::1","port":7777}
node:events:491
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED ::1:7777
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1284:16)
Emitted 'error' event on Session instance at:
at Socket.<anonymous> (C:\Users\c.mwale\Desktop\NRB API Test\Notifications Module\SMSGateway\src\SMS_Outgoing\node_modules\smpp\lib\smpp.js:119:8)
at Socket.emit (node:events:513: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) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 7777
}
I understand that there is a SMPP library for .NET documented on the inetlab website, but I am of the view this the intent of using a C# example was not to dictate the framework nor language of implementation.

failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED ---- at TCPConnectWrap.afterConnect [as oncomplete]

i am trying to get mongo db to store numbers 1 to 9999 fist it would store 0 to 1 and then 0 to 2 and so on....
for(var i = 0; i <= 9999; ++i) {
console.log(i);
a += i + " ";
add(a, i);
}
and I added another variable to the object to show the last number
and when I run this code:
var a = [];
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";
const dbName = 'numbzzz';
function add(item, lastnum) {
return new Promise(async (resolve, reject) => {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const addedItem = await db.collection('nunb').insertOne({num: item, LNUM: lastnum});
resolve(addedItem.ops[0]);
client.close();
} catch (error) {
reject(error);
}
});
}
for(var i = 0; i <= 9999; ++i) {
console.log(i);
a += i + " ";
add(a, i);
}
I got this in the log:
1
2
3
...
9999
(node:40664) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use `node --trace-warnings ...` to show where the warning was created)
D:\codde\mongoDB test\node_modules\mongodb\lib\core\topologies\server.js:438
new MongoNetworkError(
^
MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1137:16) {
name: 'MongoNetworkError'
}]
at Pool.<anonymous> (D:\codde\mongoDB test\node_modules\mongodb\lib\core\topologies\server.js:438:11)
at Pool.emit (node:events:378:20)
at D:\codde\mongoDB test\node_modules\mongodb\lib\core\connection\pool.js:562:14
at D:\codde\mongoDB test\node_modules\mongodb\lib\core\connection\pool.js:995:11
at D:\codde\mongoDB test\node_modules\mongodb\lib\core\connection\connect.js:32:7
at callback (D:\codde\mongoDB test\node_modules\mongodb\lib\core\connection\connect.js:280:5)
at Socket.<anonymous> (D:\codde\mongoDB test\node_modules\mongodb\lib\core\connection\connect.js:310:7)
at Object.onceWrapper (node:events:485:26)
at Socket.emit (node:events:378:20)
at emitErrorNT (node:internal/streams/destroy:188:8)
so I basically get the error:
D:\codde\mongoDB test\node_modules\mongodb\lib\core\topologies\server.js:438
new MongoNetworkError(
^
MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1137:16) {
name: 'MongoNetworkError'
}]
at Pool.<anonymous> (D:\codde\mongoDB test\node_modules\mongodb\lib\core\topologies\server.js:438:11)
at Pool.emit (node:events:378:20)
at D:\codde\mongoDB test\node_modules\mongodb\lib\core\connection\pool.js:562:14
at D:\codde\mongoDB test\node_modules\mongodb\lib\core\connection\pool.js:995:11
at D:\codde\mongoDB test\node_modules\mongodb\lib\core\connection\connect.js:32:7
at callback (D:\codde\mongoDB test\node_modules\mongodb\lib\core\connection\connect.js:280:5)
at Socket.<anonymous> (D:\codde\mongoDB test\node_modules\mongodb\lib\core\connection\connect.js:310:7)
at Object.onceWrapper (node:events:485:26)
at Socket.emit (node:events:378:20)
at emitErrorNT (node:internal/streams/destroy:188:8)
can someone please help me with a solution. thanks :)

Error "ConnectionError [SequelizeConnectionError]: Failed to connect to localhost:1443 - Could not connect (sequence)" using sequelize-automate

I'm getting a connection error when trying to automatically create the db table models using sequelize-automate.
However, the connection I'm using for sequelize is working but it's in a different format and I'm not sure if sequelize-automate allows me to use the same format.
const Sequelize = require('sequelize');
const util = require('util');
const dbSequelize = require('../public/dbconfigSequelize.json');
let databaseUrl = util.format(
dbSequelize.server,
dbSequelize.username,
dbSequelize.password,
dbSequelize.host,
dbSequelize.database
)
function getConnection() {
console.log('creating a new connection');
return new Sequelize(databaseUrl, {
pool: {
max: 1
},
logging: console.log
});
}
function checkAuthenticate() {
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
}
const sequelize = getConnection();
checkAuthenticate();
module.exports = sequelize;
package.json
"scripts": {
"generate-sequelize-models": "sequelize-automate -c sequelize-automate.config.json"
}
sequelize-automate.config.json
{
"dbOptions": {
"database": "mydbname",
"username": "myusername",
"password": "mypassword",
"dialect": "mssql",
"host": "localhost",
"logging": false
},
"options": {
"type": "js",
"dir": "./server/models"
}
}
The error:
PS C:\Users\username\Documents\myelectronapp> npm run generate-sequelize-models
> myelectronapp#0.1.0 generate-sequelize-models C:\Users\username\Documents\myelectronapp
> sequelize-automate -c sequelize-automate.config.json
Database options: {"database":"mydbname","username":"myusername","password":"****","dialect":"mssql","host":"localhost","port":3306,"logging":false}
Automate options: {"type":"js","camelCase":false,"dir":"./server/models","emptyDir":false}
ConnectionError [SequelizeConnectionError]: Failed to connect to localhost:3306 - Could not connect (sequence)
at C:\Users\username\Documents\myelectronapp\node_modules\sequelize\lib\dialects\mssql\connection-manager.js:134:17
at tryCatcher (C:\Users\username\Documents\myelectronapp\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (C:\Users\username\Documents\myelectronapp\node_modules\bluebird\js\release\promise.js:547:31)
at Promise._settlePromise (C:\Users\username\Documents\myelectronapp\node_modules\bluebird\js\release\promise.js:604:18)
at Promise._settlePromise0 (C:\Users\username\Documents\myelectronapp\node_modules\bluebird\js\release\promise.js:649:10)
at Promise._settlePromises (C:\Users\username\Documents\myelectronapp\node_modules\bluebird\js\release\promise.js:725:18)
at _drainQueueStep (C:\Users\username\Documents\myelectronapp\node_modules\bluebird\js\release\async.js:93:12)
at _drainQueue (C:\Users\username\Documents\myelectronapp\node_modules\bluebird\js\release\async.js:86:9)
at Async._drainQueues (C:\Users\username\Documents\myelectronapp\node_modules\bluebird\js\release\async.js:102:5)
at Immediate.Async.drainQueues [as _onImmediate] (C:\Users\username\Documents\myelectronapp\node_modules\bluebird\js\release\async.js:15:14)
at processImmediate (internal/timers.js:456:21) {
name: 'SequelizeConnectionError',
parent: ConnectionError: Failed to connect to localhost:3306 - Could not connect (sequence)
at ConnectionError (C:\Users\username\Documents\myelectronapp\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (C:\Users\username\Documents\myelectronapp\node_modules\tedious\lib\connection.js:1288:56)
at C:\Users\username\Documents\myelectronapp\node_modules\tedious\lib\connection.js:1114:21
at SequentialConnectionStrategy.connect (C:\Users\username\Documents\myelectronapp\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (C:\Users\username\Documents\myelectronapp\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:311:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
message: 'Failed to connect to localhost:3306 - Could not connect (sequence)',
code: 'ESOCKET'
},
original: ConnectionError: Failed to connect to localhost:3306 - Could not connect (sequence)
at ConnectionError (C:\Users\username\Documents\myelectronapp\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (C:\Users\username\Documents\myelectronapp\node_modules\tedious\lib\connection.js:1288:56)
at C:\Users\username\Documents\myelectronapp\node_modules\tedious\lib\connection.js:1114:21
at SequentialConnectionStrategy.connect (C:\Users\username\Documents\myelectronapp\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (C:\Users\username\Documents\myelectronapp\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:311:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
message: 'Failed to connect to localhost:3306 - Could not connect (sequence)',
code: 'ESOCKET'
}
}
Check this out, this is not from sequelize-automate but quite likely your issue is not particular to that anyway, otherwise it would be well documented by others
https://github.com/typeorm/typeorm/issues/2133
can't help but notice the error in the title is not the same as the error in your trace above either... why is it using default port for mySQL instead of mssql
In my case the error appeared because I had wrong dialect: mssql instead of mysql.
const sequelize = new Sequelize('Users', 'admin', 'pswd', {
host: 'localhost',
port: 3307,
dialect: 'mssql'
});
Updating the dialect to mysql fixed it.

How can I get a stack trace into client code with the MongoDB Node.js driver?

I've noticed that MongoDB errors offer rather useless stack traces, pointing only within the driver's internals. The line of code in the client that triggered the error is not output:
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('...', { useNewUrlParser: true }, async (err, client) => {
try {
// some mongo client code...
// some more mongo client calls...
await client.db().collection('nonexistent').drop();
// yet more mongo client calls...
} catch (e) {
console.error(e);
}
client.close();
});
Here's the output from that:
MongoError: ns not found
at Connection.<anonymous> (/home/dandv/mongostack/node_modules/mongodb-core/lib/connection/pool.js:443:61)
at Connection.emit (events.js:200:13)
at processMessage (/home/dandv/mongostack/node_modules/mongodb-core/lib/connection/connection.js:364:10)
at TLSSocket.<anonymous> (/home/dandv/mongostack/node_modules/mongodb-core/lib/connection/connection.js:533:15)
at TLSSocket.emit (events.js:200:13)
at addChunk (_stream_readable.js:290:12)
at readableAddChunk (_stream_readable.js:271:11)
at TLSSocket.Readable.push (_stream_readable.js:226:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:166:17) {
ok: 0,
errmsg: 'ns not found',
code: 26,
codeName: 'NamespaceNotFound',
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {}
}
If there's more than one mongo driver call in the try/catch block, it's impossible to tell which one generated the error.
Is there a way to have those stack traces lead up to client code?

Error connecting to heroku postgres db in nodejs

It seems after my database was upgraded to 10.2 I'm unable to connect.
I'm using the pg 7.4.2 npm package.
To be clear, I have been connecting without issue for 6 months using the same connection string which had ?ssl=true appended to it.
I get this error connecting via Pool or Client.
AssertionError [ERR_ASSERTION]: false == true
at Object.exports.connect (_tls_wrap.js:1099:3)
at Socket.<anonymous> (/home/e/express/testpg/node_modules/pg/lib/connection.js:94:23)
at Object.onceWrapper (events.js:219:13)
at Socket.emit (events.js:127:13)
at Socket.emit (domain.js:421:20)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11)
at Socket.Readable.push (_stream_readable.js:213:10)
at TCP.onread (net.js:598:20)
I'm now hardcoding the full postgres connection string so there is no issue with env variables.
I've tried adding/removing ?ssl=true to the end of the connection string and adding/removing ssl:true from the constructor. I've also tried with and without promises. Same error no matter what on both local and deployed to heroku.
imports:
import { Pool, Client } from 'pg'
method 1:
let pool = new Pool({
connectionString: csnew,
ssl: true
})
pool.connect().then( client => {
console.log('connected')
})
.catch(e=> {
console.log(e)
})
method 2:
let pgclient = new Client({
connectionString: csnew,
ssl: true
})
pgclient.connect().then( () => {
console.log('connected')
}).catch(e=> {
console.log(e)
})
That's because v7.4.2 broke its SSL support. Here's the open issue.
You need to use strictly v7.4.1 till the issue is resolved.
UPDATE
Version 7.4.3 fixed the issue.

Resources