I have deployed a mongodb replicaset which I am trying to connect to using a node js backend application.
My connection code is as follows:
mongoose.connect(config.database, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
dbName:"db7_0",
user:'****',
pass:'****'
}).catch(function (err) {
console.log('The connection to the database could not be established. Error details: ', err);
});
'config.database' is the connection URL which I have put together using the mongodb documentation and is the following:
database: "mongodb://user:pw#xxx.eu-west-1.compute.amazonaws.com:27017,xxx.eu-west-1.compute.amazonaws.com:27017,xxx.eu-west-1.compute.amazonaws.com:27017/db7_0?replicaSet=rs0"
Note: 'user', 'pw' and 'xxx' are just placeholders for the real details which I have used in the connection string.
When I start up the server and the database connection is created, my logs show the following:
And my application is throwing the following MongoNetworkError:
The connection to the database could not be established. Error details: MongoTimeoutError: Server selection timed out after 30000 ms
at Timeout._onTimeout (C:\Dev\sc\node_modules\mongoose\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
name: 'MongoTimeoutError',
[Symbol(mongoErrorContextSymbol)]: {}
}
Database error MongoTimeoutError: Server selection timed out after 30000 ms
I've tried many different approaches to fixing the issue, such as specifying the user, password and database in the connection string as well as the mongoose.connect parameters and this did not make any difference. I was initially on Mongoose v5.9.2 (now v5.8.2) and the behaviour is still the same.
Also, please note that running the following in the command prompt does work:
mongo "mongodb://user:pw#xx.xx.xxx.xx:27017/db7_0"
So i suspect it might be a mongoose error however I am struggling to figure out the issue.
It turns out that my issue was caused by the configuration of the replicaSet.
I had configured each of the members of the replicaSet using the ipv6 address of each member, which was not allowing me to connect to the replica set for some reason. I then reconfigured the replica set and changed each host address to the public DNS ipv4 address of each member and it worked.
Related
Am quiet new to backend and database. I have a solution currently using mongodb. It was working fine till yesterday when i starting having the connect ETIMEDOUT 13.37.254.237:27017 error. Nothing was changed in the URI path or tampered with. It just started and i have not been able to sort it out.
is there any help available please?
I have created another cluster and its working well. But my initial cluster that has datas which are live from clients is not connecting still.
My connection code
I have used these connections code but it has not worked. It was connecting fine all through yesterday but today without tampering with the code, couldn't connect to my mongodb
mongoose.connect(process.env.MONGO_URI,{ useNewUrlParser: true, useUnifiedTopology: true });
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URL);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.log(error);
process.exit(1);
}
};
my mongoose connection and the timedout error
Whenever you connect to Mongodb using IPs that keep updating from your system causes this kind of issues.
also this can be due to your network connection. So i will advice you to:
To allow connection from any IP address(but must ensure your URI is not made known to the public to avoid attack/ access from unwanted users.)
2.Check your network status(data)
3. Run the mongo URI on your atlas
I have a MongoDB running in a Kubernetes Pod. The Pod is forwarded to my 27017 Port on localhost. Opening localhost:21017 returns It looks like you are trying to access MongoDB over HTTP on the native driver port.. Additionaly I can connect to my DB via DataGrip.
However, when I try to create a connection with node.js it fails with the said error: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
Checking my running services under Task-Manager -> Services displays no MongoDB. However I assume that this is right since my DB is running under Kubernetes on a Remote Server. Right?
Can someone tell me what I'm doing wrong?
Here's my code:
const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/testing')
.catch(error => {
console.log("Error with message: " + error.message)
})
Update:
The above code works, if it's being executed in VSCode. When I try to run it in WebStorm it somehow doesn't. If anyone has made the same experience and knows the cause for this I'd love to know.
I am having issues connecting to MongoDb running remotely, and the connection error response I am getting from the server is somewhat weird.
My network access whitelist is set to allow all (0.0.0.0/0). Hence, my local robo3t installation was able to connect. However, I could not connect from my NodeJs code. Error is: "MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist"
IP whitelist seems to be an unlikely error, given that my local robo3t client is able to connect remotely to the same remote Mongo Atlas instance, as IP whitelist is allow-all.
How do I debug this kind of thing, please?
UPDATE: this is how I connect to MongoDb. Works well on local, too.
try {
const connectionString =
process.env.APP_ENV == "test"
? await getInMemoryMongoDbAdapter()
: `mongodb://${process.env.MONGODB_HOSTNAME}:${process.env.MONGODB_PORT}/${process.env.CBT_DATABASE_NAME}`;
logger.info(`Connecting to MongoDB service: ${connectionString}`);
await mongoose.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
} catch (error) {
reject(error);
}
The logger line correctly shows: Connecting to MongoDB service: mongodb://<user>:<password>#cluster0-xxx.yyy.zzz.net:<port>/<database>
UPDATE 2:
My localhost also does not connect via this node app; whereas my robo3t (local MongoDb client) connects. I guess that means Heroku-specific issues can now be comfortably ruled out
A decade later, I found that for the connection parameters, I needed to supply the authSource and ssl options, as below:
{
useNewUrlParser: true,
useUnifiedTopology: true,
authSource: "admin",
ssl: true,
}
Neither one works without the other. Big shout-out to #darklightcode for all the insights he gave, leading me to dig deeper. Thanks man!
I'm used to connect typeorm to atlas mongodb free instances and everything works good. Now I'm trying to connect the same way to a new serverless cluster using this configurations:
{
name: `default`,
type: `mongodb`,
url: 'mongodb+srv://user:password#production.smi5w.mongodb.net/databaseName',
useUnifiedTopology: true,
useNewUrlParser: true,
entities: [my entities]
}
I'm getting this error: MongoParseError: Text record must only set authSource or replicaSet
If I just change the url to a free cluster url everything works.
If I try to connect using the params link username, password, host etc... I'm getting a time out.
Can anyone help with this, please? Thank you so much.
I'm having an issue with trying to connect to MongoDB. I'm using mongoose here,
console.log("trying here"); // prints
await mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false
});
console.log("Mongo DB connected"); // never reached
And it throws an error
getaddrinfo ENOTFOUND cluster0-shard-00-01-abcde.mongodb.net
I have never had this error before, it used to work just fine -- not sure where to go from here. I've tried building a new cluster and network access by IP is set to public 0.0.0.0. It just keeps throwing the same error.
Note that if you specify useNewUrlParser: true, you must specify a port in your connection string,
like mongodb://localhost:27017/dbname.
The new url parser does not support connection strings that do not have a port, like mongodb://localhost/dbname.
see more info here
one more option, if you use node.js +mongo Atlas:
log in https://cloud.mongodb.com/
go to your cluster0 or
other cluster,
click connect... choose connet your application
choose node.js and then 2.2.12 or later -
you will get connection string that start with mongodb://
insted of mongodb+srv:// (for node js 3.0 or later)
I was facing same error.
How are you using your mongo connection string? and what is your mongoose version?
if your using a latest version of mongoose try using like below string
I changed my string from
mongodb://<user>:<password>...
to
mongodb+srv://<user>:<password>...
check your CONNECTION :
Quick fix is checking your connection, this error happens while your connection is not stable and it've tried to connect more than 30 sc without any success.
//checks connection status
mongoose.connection.on("connected", () => console.log("mongoDb connected!"));
mongoose.connection.on("disconnected", () => console.log("mongoDb disconnected!"));