MongoServerError: bad auth : Authentication failed. despite all solutions - mongodb

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.

Related

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

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!

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.

node-mysql pool experiences ETIMEDOUT

I have a node-mysql pool configuration of
var db_init={
host : 'ip_address_of_GCS_SQL',
user : 'user_name_of_GCS_SQL',
password : 'password here',
database : 'db here',
supportBigNumbers: true,
connectionLimit:100
};
Pool was created using
GLOBAL.db_foobar = mysql.createPool(db_init);
I basically just left the connection on for a couple of hours and I saw this error reported by my connection.query Request (after getConnection of course):
prodAPI-104 (out): { status: 'Error',
prodAPI-104 (out): details: '[foobar_function]Error in query',
prodAPI-104 (out): err: '{ [Error: read ETIMEDOUT]\n code: \'ETIMEDOUT\',\n errno: \'ETIMEDOUT\',\n syscall: \'read\',\n fatal: true }',
prodAPI-104 (out): query: 'SELECT * FROM `foobar_table`;' }
Why is this happening? The MySQL in Google-Cloud-SQL didn't report a query taking too long to create so I dunno why this happened.
I suspect the reason is that keepalive is not enabled on the connection to the MySQL server.
node-mysql does not have an option to enable keepalive and neither does node-mysql2, but node-mysql2 provides a way to supply a custom function for creating sockets which we can use to enable keepalive:
var mysql = require('mysql2');
var net = require('net');
var pool = mysql.createPool({
connectionLimit : 100,
host : '123.123.123.123',
user : 'foo',
password : 'bar',
database : 'baz',
stream : function(opts) {
var socket = net.connect(opts.config.port, opts.config.host);
socket.setKeepAlive(true);
return socket;
}
});