Error connecting to Atlas Free Cluster (MongoDB) - node.js

TL;DR: Can't connect to Atlas Cluster even after doing exactly what docs said.
Hi, so I read the docs of getting started with Atlas and everything seemed nice & easy. I did follow the steps, created a free cluster, whitelisted my IP, and then tried to connect using their sample app:
const { MongoClient } = require("mongodb");
// Replace the following with your Atlas connection string
const url = "mongodb+srv://<username>:<password>#clustername.mongodb.net/test?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true";
const client = new MongoClient(url);
async function run() {
try {
await client.connect();
console.log("Connected correctly to server");
} catch (err) {
console.log(err.stack);
}
finally {
await client.close();
}
}
run().catch(console.dir);
But the following error occurred when I tried to execute with: node connect.js
PS C:\Users\marjo\Documents\mongoDB Atlas> node connect
(node:11352) DeprecationWarning: 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.
MongoNetworkError: failed to connect to server [remote-doc-shard-00-02-otc5a.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\auth_provider.js:46:25
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\scram.js:240:11
at _callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:349:5)
at Connection.messageHandler (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:378:5)
at Connection.emit (events.js:315:20)
at processMessage (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connection.js:384:10)
at TLSSocket.<anonymous> (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connection.js:553:15)
at TLSSocket.emit (events.js:315:20)
at addChunk (_stream_readable.js:297:12)
at readableAddChunk (_stream_readable.js:273:9) {
ok: 0,
code: 8000,
codeName: 'AtlasError'
}]
at Pool.<anonymous> (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\topologies\server.js:438:11)
at Pool.emit (events.js:315:20)
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\pool.js:561:14
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\pool.js:1008:9
at callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:97:5)
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:396:21
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\auth_provider.js:66:11
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\scram.js:240:11
at _callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:349:5)
at Connection.messageHandler (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:378:5)
I tried changing the connection string with the one from Atlas: (because it was different from the docs by a tiny bit)
const uri = "mongodb+srv://Marjo:<password>#remote-doc-otc5a.mongodb.net/<dbname>?retryWrites=true&w=majority";
But still the same result. My password had a !character so I put %21 instead of it. I also replaced with cluster name (Remote-Doc) and test but it still failed.
I'd appreciate if you could help me!

I think that you are having a problem with the parse of your password, maybe it has special characters.
The best way to handle this is to change the way that you are connecting to pass the user and password as options.
You can follow the doc and change your MongoClient conection for something like this:
const mongoclient = new MongoClient(new Server("remote-doc-otc5a.mongodb.net", 27017));
// Listen for when the mongoclient is connected
mongoclient.open(function (err, mongoclient) {
// Then select a database
const db = mongoclient.db("dbname");
// Then you can authorize your self
db.authenticate('username', 'password', (err, result) => {
// On authorized result=true
// Not authorized result=false
// If authorized you can use the database in the db variable
});
});
And with mongoose you can do something like this:
mongoose.connect('mongodb+srv://#remote-doc-otc5a.mongodb.net/test?retryWrites=true&w=majority', {
user: 'USERNAME',
pass: 'PASSWORD',
useNewUrlParser: true,
useUnifiedTopology: true
})
Also, check if you are not using the account password instead of the cluster/database password.
You can follow this tutorial to check if you are using the correct one: MongoDB Atlas Setup - Digital Ocean.

I just changed the Atlas password to a simple one with no special characters, and the connection worked! I feel ashamed now

Related

MongoError: Unsupported OP_QUERY command: insert

I have been new to MongoDB and I am trying to connect mongodb using nodejs application.
whenever i try to run the nodejs file an error is being raised.
MongoError: Unsupported OP_QUERY command: insert. The client driver may require an upgrade. For more details see https://dochub.mongodb.org/core/legacy-opcode-removal
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'conFusion';
const client = new MongoClient(url);
client.connect()
.then((client) => {
console.log('Connected correctly to server');
const db = client.db(dbName);
const collection = db.collection('dishes');
collection.insertOne({name: "Uthapizza", description: "test"})
.then((result) => {
console.log('Insert Document:\n', result.ops);
return collection.find({}).toArray();
})
.then((docs) => {
console.log('Found Documents:\n', docs);
return collection.deleteMany({});
})
.then((result) => {
console.log('Deleted Documents:\n', result);
return client.close();
})
.catch((err) => console.log(err));
})
I have been using mongoDB latest version 6.0 and i am not able to perform the insertion operation using my node application.
Connected correctly to server
MongoError: Unsupported OP_QUERY command: insert. The client driver may require an upgrade. For more details see https://dochub.mongodb.org/core/legacy-opcode-removal
at C:\Users\koushik\OneDrive\Desktop\Nodejs\node-mongo\node_modules\mongodb-core\lib\connection\pool.js:593:63
at authenticateStragglers (C:\Users\koushik\OneDrive\Desktop\Nodejs\node-mongo\node_modules\mongodb-core\lib\connection\pool.js:516:16)
at Connection.messageHandler (C:\Users\koushik\OneDrive\Desktop\Nodejs\node-mongo\node_modules\mongodb-core\lib\connection\pool.js:552:5)
at emitMessageHandler (C:\Users\koushik\OneDrive\Desktop\Nodejs\node-mongo\node_modules\mongodb-core\lib\connection\connection.js:309:10)
at Socket.<anonymous> (C:\Users\koushik\OneDrive\Desktop\Nodejs\node-mongo\node_modules\mongodb-core\lib\connection\connection.js:452:17)
at Socket.emit (node:events:527: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:190:23) {
ok: 0,
errmsg: 'Unsupported OP_QUERY command: insert. The client driver may require an upgrade. For more details see https://dochub.mongodb.org/core/legacy-opcode-removal',
code: 352,
codeName: 'UnsupportedOpQueryCommand'
}
Please Help Me with this Problem and Please Mention The Solution. What Should I do To perform the operation as it is not working and op_query is deprecated in latest version.
The error says what you need to do (ie use latest mongo node driver). Latest servers stopped supporting legacy OP_INSERT/OP_QUERY wire protocols

Connect to a remote server mongoDB in Docker via ssh in nodeJS using tunnel-ssh, AuthenticationFailed

I am trying to connect to a remote server MongoDB in Docker through ssh in Nodejs as below :
sshConfig = {
username: 'username',
password: 'password',
host: 'host',
port: 22,
dstHost: '172.17.0.3',
dstPort: 27017,
localPort: 5000
};
const uri = 'mongodb://admin:password#localhost:27017/admin';
tunnel(sshConfig, async error => {
if (error) {
throw new Error(`SSH connection error: ${error}`);
}
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('admin').command({ ping: 1 });
console.log('Connected successfully to server');
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
await run().catch(console.dir);
});
But I am getting error as below :
MongoServerError: Authentication failed.
at MessageStream.messageHandler (/node_modules/mongodb/src/cmap/connection.ts:740:20)
at MessageStream.emit (node:events:390:28)
at MessageStream.emit (node:domain:475:12)
at processIncomingData (/node_modules/mongodb/src/cmap/message_stream.ts:167:12)
at MessageStream._write (/node_modules/mongodb/src/cmap/message_stream.ts:64:5)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)
at MessageStream.Writable.write (node:internal/streams/writable:334:10)
at Socket.ondata (node:internal/streams/readable:754:22)
at Socket.emit (node:events:390:28) {
ok: 0,
code: 18,
codeName: 'AuthenticationFailed'
},
and I open http://localhost:5000/ by browser, it shows that:
It looks like you are trying to access MongoDB over HTTP on the native driver port.
I can connect the database via:
Use MongoDB compass to connect the database via ssh
Use mongo 'mongodb://admin:password#remote-host:27017/admin' in local machine terminal
Use MongoClient(mongodb://admin:password#remote-host:27017/admin) in Nodejs without ssh-tunnel
Use mongo 'mongodb://admin:password#localhost:27017/admin' in both remote host and remote host docker contaniner
I am sure the password is correct.

Mongoose claims I have extra / in DB uri though I do not think I do

I was forced to move DB clusters so I have a new connection string and no actual code changes in the application were made.
When I try to start the application I get the below error message using the following connection string(s), I've included my old one and new one. This cluster is running on Mongo Atlas as a M10 cluster.
Old
mongodb+srv://<myusername>:<mypassword>#production-m0-<account ID?>.mongodb.net
New
mongodb+srv://<myusername>:<mypassword>#production.<account ID?>.mongodb.net
Error message/log
/opt/node_app/node_modules/mongodb/lib/topologies/replset.js:346
throw err;
^
MongoError: database names cannot contain the character '/'
at Function.create (/opt/node_app/node_modules/mongodb-core/lib/error.js:43:12)
at validateDatabaseName (/opt/node_app/node_modules/mongodb/lib/operations/db_ops.js:728:24)
at new Db (/opt/node_app/node_modules/mongodb/lib/db.js:182:3)
at MongoClient.db (/opt/node_app/node_modules/mongodb/lib/mongo_client.js:237:14)
at /opt/node_app/node_modules/mongoose/lib/connection.js:564:62
at /opt/node_app/node_modules/mongodb/lib/utils.js:410:17
at executeCallback (/opt/node_app/node_modules/mongodb/lib/utils.js:402:9)
at /opt/node_app/node_modules/mongodb/lib/operations/mongo_client_ops.js:286:5
at connectCallback (/opt/node_app/node_modules/mongodb/lib/operations/mongo_client_ops.js:265:5)
at /opt/node_app/node_modules/mongodb/lib/operations/mongo_client_ops.js:417:5
at ReplSet.connectHandler (/opt/node_app/node_modules/mongodb/lib/topologies/replset.js:343:9)
at Object.onceWrapper (events.js:300:26)
at ReplSet.emit (events.js:210:5)
at /opt/node_app/node_modules/mongodb-core/lib/topologies/replset.js:786:18
at processTicksAndRejections (internal/process/task_queues.js:75:11) {
driver: true,
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {}
}
Code used in application
const dbString =`${config.db}/mydb?retryWrites=true&w=majority`
mongoose.connect(dbString, { autoReconnect: true, useNewUrlParser: true }, (err) => {
if (!err) console.log('MongoDB has connected successfully.')
});
EDIT as requested combined UrI
mongodb+srv://<myusername>:<mypassword>#production.<account ID?>.mongodb.net/mydb?retryWrites=true&w=majority

Node-Postgres SequelizeConnectionError: password authentication failed for user

I am developping a backend application with node and sequelize. My database is from postgresql.
When lauching the app, the database connection works fine, but when it tries to communicate with the database to read or update, it fails with a connection error:
password authentication failed for user "wushin".
Seems really weird to me because database connection has already been done, and password has been validated. Do you guys know what's happening ? Maybe an issue with pg module but I tried different versions.
Versions
Node: 10.17.0
Sequelize: 5.21.3
Postgres: 10.11
pg module: 7.17.1
-> This code works fine:
const sequelize = new Sequelize(process.env.DATABASE_DEV_URL)
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.\n')
})
.catch(err => {
console.error('Unable to connect to the database:', err)
})
-> But this promise fails with SequelizeConnectionError:
models.Question.findAll()
.then(data => {
console.log('-> Succeeded data fetching\n')
console.log(data)
})
.catch(err => {
console.log('-> Failed data fetching\n')
console.log('Error', err)
})
Logs:
yarn run v1.19.2
$ node index.js
Example app listening on port 4000 or something!
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
- Trying to fetch data:
-> Failed data fetching
Error:
{ SequelizeConnectionError: password authentication failed for user "wushin"
at connection.connect.err (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:182:24)
at Connection.connectingErrorHandler (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/pg/lib/client.js:194:14)
at Connection.emit (events.js:198:13)
at Socket.<anonymous> (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/pg/lib/connection.js:128:12)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:287:12)
at readableAddChunk (_stream_readable.js:268:11)
at Socket.Readable.push (_stream_readable.js:223:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'SequelizeConnectionError'
It seems that you pass no configurations to Sequelize but the host. The minimum configurations are host, port, databasename, dialect username, and password.
From the docs:
const Sequelize = require('sequelize');
// Option 1: Passing parameters separately const sequelize = new
Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
});
// Option 2: Passing a connection URI const sequelize = new
Sequelize('postgres://user:pass#example.com:5432/dbname');
I finally fixed this. The issue was that with sequelize, requiring the models calls an index.js that is supposed to do the sequelize connection for you, using the config repository sequelize creates.
My connection to sequelize was working well but the one that was launched by requiring models had some bad information on my database.
Therefore I could not use the imported model to fetch data on the database.
I inserted good config information :
require('dotenv').config()
module.exports = {
development: {
url: process.env.DATABASE_URL,
dialect: 'postgres',
},
test: {
url: process.env.DATABASE_TEST_URL,
dialect: 'postgres',
},
production: {
url: process.env.DATABASE_PROD_URL,
dialect: 'postgres',
},
}
And completely removed the line that I wrote myself:
const sequelize = new Sequelize(process.env.DATABASE_DEV_URL)
It is now the models/index.js that connects to the database with :
const sequelize = new Sequelize(process.env.DATABASE_URL)
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.\n')
})
.catch(err => {
console.error('Unable to connect to the database:', err)
})

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