Problem connecting to Mongodb Atlas - Error: "querySrv ECONNREFUSED" - mongodb

I have created a free cluster for mongodb atlas. Under that cluster I have created a database and a collection to test things out. As I was using node js driver 4.0 or above, this is the connection string I got:
mongodb+srv://myName:myPass#cluster0.2sjva.mongodb.net/myDb?retryWrites=true&w=majority
This is my backend code:
const { MongoClient } = require("mongodb");
// Connection URI
const uri =
"mongodb+srv://myName:myPass#cluster0.2sjva.mongodb.net/myDb?retryWrites=true&w=majority";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server
await client.connect();
// Establish and verify connection
await client.db("myDb").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
But when I run this code, I get this following error:
Error: querySrv ECONNREFUSED _mongodb._tcp.cluster0.2sjva.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:210:19) {
errno: undefined,
code: 'ECONNREFUSED',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster0.2sjva.mongodb.net'
}
Here is some information I can provide:
I have whitelisted my current Ip address, After this error I used 0.0.0.0. But the problem persists.
Os: Arch linux
I have also tried to use this connection string for older driver version: mongodb://... and that worked.
My question: why connection string for node js driver version > 4.0 doesn't work in my case?
Thank you for reading!

Related

MongoServerError: bad auth : Authentication failed. despite all solutions

Hi all so I went through the MERN Stack tutorial: https://www.mongodb.com/languages/mern-stack-tutorial.
Am not able to connect successfully to MongoDB.
Server is running on port: 8080
MongoServerError: bad auth : Authentication failed.
at Connection.onMessage (/Users/username/Documents/Projects/projectname/server/node_modules/mongodb/lib/cmap/connection.js:227:30)
at MessageStream.<anonymous> (/Users/username/Documents/Projects/projectname/server/node_modules/mongodb/lib/cmap/connection.js:60:60)
at MessageStream.emit (node:events:513:28)
at processIncomingData (/Users/username/Documents/Projects/projectname/server/node_modules/mongodb/lib/cmap/message_stream.js:125:16)
at MessageStream._write (/Users/username/Documents/Projects/projectname/server/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
at writeOrBuffer (node:internal/streams/writable:392:12)
at _write (node:internal/streams/writable:333:10)
at Writable.write (node:internal/streams/writable:337:10)
at TLSSocket.ondata (node:internal/streams/readable:766:22)
at TLSSocket.emit (node:events:513:28) {
ok: 0,
code: 8000,
codeName: 'AtlasError',
connectionGeneration: 0,
[Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }
The 'config.env' file contains this:
ATLAS_URI=mongodb+srv://correctusername:correctpassword#atlascluster.zgubjgl.mongodb.net/employees?retryWrites=true&w=majority
PORT=8080
The 'conn.js' contains:
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var _db;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
// Verify we got a good "db" object
if (db)
{
_db = db.db("employees");
console.log("Successfully connected to MongoDB.");
}
return callback(err);
});
},
getDb: function () {
return _db;
},
};
Solutions attempted:
Ensured that the username and password do not have '<>' enclosing them.
Created a new user in 'Database Access' in MongoDB itself with 'readWriteAnyDatabase#admin' access to mirror the ending of the ATLAS_URI connection string, same error.
Removed 'employees' in connection string and tried again, same error.
Tried another database name in both 'config.env' and 'conn.js' files, same error.
Ensured that my 'Network Access' in MongoDB itself is '0.0.0.0/0 (includes your current IP address)'.
Ensured that cluster name matches.
All of the solutions above are things I tried based off what I have researched on Stack. Is the problem that I don't have an employees database set up on MongoDB itself? Or is it a security setting on my Mac that is causing an issue?
Please help - feeling very downtrodden that I have reached this obstacle as I have a really good platform idea to start a business based on.

Atlas mongoDB cloud service with dart package mongo_dart cause Connection Exception

I'm trying to write into Atlas mongoDB cloud service with dart package mongo_dart.
This is how to connect to:
static const String uri =
"mongodb+srv://User:Password#Project.e0nro.mongodb.net/DbName?retryWrites=true&w=majority&tls=true";
Future<Db> connectToDatabase() async {
var db = await Db.create(uri);
await db.open(secure: true);
print('Connected to database');
return db;
}
And this is how to update my data:
await coll.update(
{
"symbol": symbol,
},
{
r"$addToSet": {"pens": pen.toJson()}
},
);
I've got this error rapidly:
Unhandled exception:
MongoDB ConnectionException: connection closed: The socket connection has been reset by peer.
Possible causes:
- Trying to connect to an ssl/tls encrypted database without specifiyng
either the query parm tls=true or the secure=true parameter in db.open()
- Others
And sometimes this one:
Unhandled exception:
MongoDB ConnectionException: connection closed: SocketException: Read failed (OS Error: Connection reset by peer, errno = 104), address = ????.e0nro.mongodb.net, port = 52508
In Atlas panel I added the IP address to access the database globally
0.0.0.0/0 (includes your current IP address) access Active
How can I solve these errors?

Deno Uncaught Error: No such host is known. (os error 11001)

I tried to connect the MongoDB Atlas to my Deno Application using https://deno.land/x/mongo#v0.21.2 framework. I tried the below code to run my application. but I get an error No such host is known. (os error 11001) What went wrong here
Error
error: Uncaught Error: No such host is known. (os error 11001)
at unwrapResponse (rt\10_dispatch_json.js:24:13)
at sendAsync (rt\10_dispatch_json.js:75:12)
at async Object.connect (rt\30_net.js:221:13)
at async MongoClient.connect (client.ts:41:14)
at async mongodb.ts:33:1
Mongodb.ts File
import { MongoClient } from "https://deno.land/x/mongo#v0.21.0/mod.ts";
const client1 = new MongoClient();
await client1.connect("mongodb+srv://user1:MYPASSWORD#cluster0.hmdnu.mongodb.net/TestingDB?retryWrites=true&w=majority");
const db = client1.database("TestingDB");
export default db;
I used this command to run my server
deno run --allow-net --allow-write --allow-read --allow-plugin --unstable server.ts
I fixed this using https://www.youtube.com/watch?v=hhdhydffKKE this video reference
Follow these steps to fix this
import { MongoClient } from "https://deno.land/x/mongo#v0.21.0/mod.ts";
const client1 = new MongoClient();
await client.connect({
db: "<db>",
tls: true,
servers: [
{
host: "<host>",
port: 27017,
},
],
credential: {
username: "<user>",
password: "<password>",
db: "<db>",
mechanism: "SCRAM-SHA-1",
},
});
const db = client1.database("TestingDB");
export default db;
This is not mentions in the document, but this will help to fix the issue
<db> is the database name, you can get the database name by following these steps
Step-1
Step-2
To find the <host> follow these steps
Step -1
Step -2
Step -3

Unknown auth message code 1397113172 when connect to Heroku postgres

Thanks reading my issue.
Currently, I am using postgres (hobby-dev) on Heroku and facing this issue every time that I connect to the database.
error: Uncaught (in promise) Error: Unknown auth message code 1397113172
throw new Error(`Unknown auth message code ${code}`);
^
at Connection.handleAuth (connection.ts:197:15)
at Connection.startup (connection.ts:155:16)
at async Pool._createConnection (pool.ts:32:5)
at async pool.ts:61:7
at async Promise.all (index 0)
at async Pool._startup (pool.ts:63:25)
My application using Deno now
import { Pool } from "https://deno.land/x/postgres/mod.ts";
import { config } from "./config.ts";
const port = config.DB_PORT ? parseInt(config.DB_PORT || "") : undefined;
const POOL_CONNECTIONS = 20;
const dbPool = new Pool({
port,
hostname: config.DB_HOST,
user: config.DB_USER,
database: config.DB_NAME,
password: config.DB_PASS
}, POOL_CONNECTIONS);
export { dbPool };
Here is debug screen.
I have found this issue post and it mentioned about lacking ssl. Not sure how to do it on heroku.
I have tried some solutions, even change lib to pg and it still not work. I am very appreciated if any clue or help to fix this issue.
Note:
I read a document on heroku about "Heroku Postgres Connection Pooling is not available for Hobby-tier databases.". Then I switched to use Client with syntax similar like this to connect to Heroku postgres this:
import { Client } from "https://deno.land/x/postgres/mod.ts";
let config;
config = {
hostname: "localhost",
port: 5432,
user: "user",
database: "test",
applicationName: "my_custom_app"
};
// alternatively
config = "postgres://user#localhost:5432/test?application_name=my_custom_app";
const client = new Client(config);
await client.connect();
await client.end();
ref: https://deno-postgres.com/#/

Unable to connect to postgres using deno.js

Unable to connect to postgres in deno.js.
Here is the configuration:
const dbCreds = {
applicationName: "appname",
user: "user_sfhjwre",
database: "d9iu8mve7nen",
password: "68790f31eelkhlashdlkagsvADSDa52f9d8faed894c037ef6f9c9f09885603",
hostname: "ec2-345-34-97-212.eu-east-1.xx.amazonaws.com",
port: 5432,
};
export { dbCreds };
Usage:
import { Client } from "https://deno.land/x/postgres/mod.ts";
import { dbCreds } from "../config.ts";
const client = new Client(dbCreds);
await client.connect();
Also tried:
config = "postgres://user#localhost:5432/test?application_name=my_custom_app";
const client = new Client(config);
await client.connect();
Same result:
Uncaught Error: Unknown auth message code 1397113172
Is there anything wrong with the syntax, I can connect to the same db using prisma.
I have the PostgreSQL server in a remote server and, each time my public IP changes, I need to change the pg_hba.conf in order to set my new public IP as authorized for remote access.
Hope this helps.
Best regards.