Mongodb connectionString can't connect - mongodb

I can connect via Mongodb COMPASS using my username and password but apparently i can't connect it to my website.
mongodb://localhost:27017/mydb works fine in connection string but not atlas/online cluster
{"connectionString":"mongodb+srv://myuser:mypass#thiscluster.azure.mongodb.net/mydb?retryWrites=true&w=majority"
,"secret":""}
Error :
Server listening on port 3000
Unhandled rejection MongoError: not authorized on admin to execute command { lis
tIndexes: "sessions", cursor: { } }
at Function.MongoError.create (C:\Users\user\Documents\GitHub\meanie\serv
er\node_modules\mongodb-core\lib\error.js:31:11)
at queryCallback (C:\Users\user\Documents\GitHub\meanie\server\node_modul
es\mongodb-core\lib\cursor.js:212:36)
at C:\Users\user\Documents\GitHub\meanie\server\node_modules\mongodb-core
\lib\connection\pool.js:469:18
at processTicksAndRejections (internal/process/task_queues.js:79:11)
I am using MEANIE STACK BLOG
Reference : Cloud mongodb guide
mongodb+srv://:#thiscluster.azure.mongodb.net/?retryWrites=true&w=majority
Other reference : https://docs.mongodb.com/manual/reference/connection-string/

SOLVED
config.json / node's "connectionString" can't be parsed using mongo+srv://user:pw#thiscluster.mongodb.com/mydb?thisoptions
node version i'm using is 2.2 12
fixed via :
"connectionString":"mongodb://user:pass#test-shard-00-00-sample.azure.mongodb.net:27017,test-shard-00-01-sample.azure.mongodb.net:27017,test-shard-00-02-sample.azure.mongodb.net:27017/THISDB?ssl=true&replicaSet=Test-shard-0&authSource=admin&retryWrites=true&w=majority",

Related

Cannot connect to Atlas MongoDB from Azure Functions

I just created an Azure Function that should connect to my instance of MongoDB on Atlas, basically following this tutorial:
https://www.mongodb.com/blog/post/how-to-integrate-azure-functions-with-mongodb
From my local development with Visual Studio, everything works fine and I can connect to the Atlas environment, but when I deploy the code on Azure, the following exception raises:
A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/ltdevcluster-shard-00-00.qkeby.mongodb.net:27017" }", EndPoint: "Unspecified/ltdevcluster-shard-00-00.qkeby.mongodb.net:27017", ReasonChanged: "Heartbeat", State: "Disconnected", ServerVersion: , TopologyVersion: , Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server.
---> MongoDB.Driver.MongoConnectionException: An exception occurred while receiving a message from the server.
---> System.IO.EndOfStreamException: Attempted to read past the end of the stream.
If I instead set the Network Access to "everywhere", again everything works fine.
Now, in the Network Access panel of Atlas, I added the IPs retrieved from the Azure Portal under my function app => Networking => Inbound traffic and Outbound traffic (a total of 1 IP for inbound and 3 IPs for outbound).
But adding those 4 IPs has not solved the issue.
What else should I do?
If you are using static IP, for a workaround, you can check this: How do I set a static IP in Functions?
You can also set up a Private Endpoint and for the security of the database credentials check secrets engine integration using vault.
You can refer to How to connect Azure Function with MongoDB Atlas ,Azure functions unable to connect with Mongo Db Atlas M10 and How to connect Azure Function with MongoDB Atlas

strapi mongo flutter app connection error

When I install strapi via npm, then run "strapi new server" and then try to connect to mongodb atlas; It shows the following error.
(node:12564) 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.
⛔️ Connection test failed: failed to connect to server [oriapp-shard-00-01.pjvsw.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to oriapp-shard-00-01.pjvsw.mongodb.net:27017 closed
at TLSSocket. (C:\Users\Sharm\AppData\Local\Temp\strapi236c8a243294\node_modules\strapi-connector-mongoose\node_modules\mongodb\lib\core\connection\connection.js:356:9)
at Object.onceWrapper (events.js:422:26)
at TLSSocket.emit (events.js:315:20)
at TLSSocket.EventEmitter.emit (domain.js:483:12)
at net.js:674:12
at TCP.done (_tls_wrap.js:567:7) {
[Symbol(mongoErrorContextSymbol)]: {}
}]
So , the solution to the above problem:
Reinstall strapi using npm or yarn or any other package manager.
The ip whitelist in mongodb atlas in your cluster should have the ip address of your system.
when aysnchronous function is defined use Ipv4 in place of "localhost:1337".
Thus one will be good to go.

MongoDB unable to connect to one MongoDB instance from another MongoDB instance using connect() Description

I am trying to access a MongoDB collection in my QA env from my Dev env. I am trying to achive something similar to
DBLink (Database Link) in Oracle.
MongoDB version = 3.4.4
RoboMongo = 0.9.0-RC10
Example of how i am trying to establish Database Link
[Note - my mongoDB Dev instance is not password protected]
Case 1 : Connect QA from DEV
Login to MongoDB Dev Instance in Robomongo and then run below query.
var db2 = connect('<SERVER_NAME>:<PORT>/<QA_DB_NAME>')
Output:-
connecting to: <SERVER_NAME>:<PORT>/<QA_DB_NAME>
Error: socket exception [CLOSED] for <SERVER_IP>:<PORT> :
connect#src/mongo/shell/mongo.js:226:14
#(shell):1:15
Case 2 : Connect DEV from QA
var db2 = connect('<SERVER_NAME>:<PORT>/<DEV_DB_NAME>', '<USERNAME>', '<PASSWORD>')
Login to MongoDB QA Instance in Robomongo and then run below query.
var db2 = connect(':/')
Output:-
connecting to: <SERVER_NAME>:<PORT>/<QA_DB_NAME>
Error: network error while attempting to run command 'isMaster' on host '<SERVER_NAME>:<PORT>' :
connect#src/mongo/shell/mongo.js:226:14
#(shell):1:15

Unable to connect to MongoDb using MongoClientSettings as parameter to MongoClient

I am developing a C# MVC Web API which uses MongoDb as backend.I tried connecting to my mongodb database using
MongoClient mongoClient = new MongoClient(connectionString)
where connectionstring is in format : mongodb://Username:Password#hostname.eastus.cloudapp.azure.com
Mongo db is hosted in a virtual machine in Azure.I am able to connect to the database and all works good.But I am getting frequent exceptions:
"MongoDb.driver.MongoConnectionException".An exception occurred while
receivinf a message from server--->System.IO.IOException:Unable to
read data from the transport connection : A connection attempt failed
because the connected party did not properly respond after a period of
time,......"
So after a bit of research I have learnt that Azure is killing idle connections and I have to set MaxConnectionIdleTime.
In order to set MaxConnectionIdleTime I decided to connect to Mongodb in the below way
var credential = MongoCredential.CreateCredential("dbname", "UserName", "Password");
var settings = new MongoClientSettings
{
Credentials = new[] { credential },
Server = new MongoServerAddress("HostName", 27017),
MaxConnectionIdleTime = new TimeSpan(0, 3, 0)
};
MongoClient mongoClient = new MongoClient(settings);
In this case I am using the same username,password combination given in the connection string which I used to connect before.
While trying to connect here I am getting inner Exception:
MongoDB.Driver.MongoAuthenticationException: "Unable to authenticate
using sasl protocol mechanism SCRAM-SHA-1".
"MongoDb.driver.MongoConnectionException".An exception occurred while receivinf a message from server--->System.IO.IOException:Unable to read data from the transport connection : A connection attempt failed because the connected party did not properly respond after a period of time,....
The reason behind this exception is when hosted in Azure,Azure tries to kill the idle connections but the C# driver is not aware of this.The driver tries to execute queries on the killed connections without knowing the connection is not existing.
The solution that worked out for me is to set maxIdleTimeMS=45000 in connection string.
This way driver will not use a connection which has been idle for long time.
Here is the connection string that worked out for me
connectionString="Username:Password#hostname.eastus.cloudapp.azure.com/?connectTimeoutMS=30000&socketTimeoutMS=30000&waitQueueTimeoutMS=30000&maxIdleTimeMS=45000"
I have had a similar error with my Azure hosted MongoDb (Cosmos Db). It turned out to be network settings such that I had blocked all access. Changing it to Allow access from "All networks" fixed the issue.
The error is very misleading, I would have expected a connection timeout.
A timeout occured after 30000ms selecting a server using
CompositeServerSelector{ Selectors =
MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector,
LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000
} }. Client view of cluster state is { ClusterId : "1", ConnectionMode
: "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers :
[{ ServerId: "{ ClusterId : 1, EndPoint :
"Unspecified/XXXX.documents.azure.com:10255" }", EndPoint:
"Unspecified/XXXX.documents.azure.com:10255", State: "Disconnected",
Type: "Unknown", HeartbeatException:
"MongoDB.Driver.MongoConnectionException: An exception occurred while
opening a connection to the server. --->
MongoDB.Driver.MongoAuthenticationException: Unable to authenticate
using sasl protocol mechanism SCRAM-SHA-1. --->
MongoDB.Driver.MongoCommandException: Command saslContinue failed: Not
Authenticated.
To troubleshot I tried from MongoDb Compass as well and that didn't work either, showing me it wasn't the code.

MongoDB db.serverStatus() gives error when running using tunnel that is targeted to api.cloudfoundry.com

Following is the console session...
C:\Users\xxx>vmc tunnel myMongoDB
Getting tunnel connection info: OK
Service connection info:
username : uuuu
password : pppp
name : db
url : mongodb://uuuu:pppp#172.30.xx.xx:25200/db
Starting tunnel to myMongoDB on port 10000.
1: none
2: mongo
3: mongodump
4: mongorestore
Which client would you like to start?: 2
Launching 'mongo --host localhost --port 10000 -u uuuu -p pppp db'
MongoDB shell version: 2.0.6
connecting to: localhost:10000/db
> db.serverStatus()
{ "errmsg" : "need to login", "ok" : 0 }
>
Which credentials should I use to login (assuming should use db.auth) to get rid of the error "{ "errmsg" : "need to login", "ok" : 0 }".
When I run the same in micro CF on my machine it works ok and gives me the expected output.
P.S. I'm trying this to get to know the current connections on my application, written in node.js. Trying to debug some issues with connections to the DB. If there is any other alternative that I can use please suggest that as well.
this should work! Not sure why your tunnel isn't connecting, my immediate suggestion is to try another instance of MongoDB and see if the same error occurs.
If you are trying to inspect the bound services on you node.js app you should be able to inspect them in the VCAP_SERVICES environment variable. For example;
var http = require('http');
var util = require('util');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(util.inspect(process.env.VCAP_SERVICES));
res.write("\n\n************\n\n");
res.end(util.inspect(req.headers));
}).listen(3000);
This code is currently running at http://node-headers.cloudfoundry.com/ to serve as an example. However, mongodb connections for node.js applications should automatically configure to the bound service. If this does not work for you, then please do let me know.