MongoTimeoutError: Server selection timed out after 10000 ms - node.js

I am trying to create a MERN app and containerize it with docker and manage the containers using kubernetes (minikube).
When I try to run the nodejs container it logs the following error
Server v8 up and running on port 5000 !
MongoTimeoutError: Server selection timed out after 10000 ms
at Timeout._onTimeout (/home/app/node_modules/mongodb-core/lib/sdam/topology.js:773:16)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
[Symbol(mongoErrorContextSymbol)]: {}
}
The code at server.js is as follows:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
// the connection string when using username and password in mongodb-server
// mongodb://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}#mongodb-service:27017/exam?authSource=${process.env.MONGO_DB_USERNAME}
mongoose
.connect("mongodb://mongodb-service/exam", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log(`MongoDB successfully connected`))
.catch((err) => console.log(err));
The logs in mongodb container are as follows:
{"t":{"$date":"2022-12-16T14:28:58.316+00:00"},"s":"I", "c":"COMMAND", "id":51803, "ctx":"LogicalSessionCacheRefresh","msg":"Slow query","attr":{"type":"command","ns":"config.system.sessions","command":{"createIndexes":"system.sessions","v":2,"indexes":[{"key":{"lastUse":1},"name":"lsidTTLIndex","expireAfterSeconds":1800}],"ignoreUnknownIndexOptions":false,"writeConcern":{},"$db":"config"},"numYields":0,"reslen":114,"locks":{"ParallelBatchWriterMode":{"acquireCount":{"r":5}},"FeatureCompatibilityVersion":{"acquireCount":{"r":5,"w":1}},"ReplicationStateTransition":{"acquireCount":{"w":5}},"Global":{"acquireCount":{"r":5,"w":1}},"Database":{"acquireCount":{"r":4,"w":1}},"Collection":{"acquireCount":{"r":5,"w":1}},"Mutex":{"acquireCount":{"r":8}}},"storage":{},"protocol":"op_msg","durationMillis":529}}
If I should provide more details please tell me
Thanks in advance

Related

Connection to MongoDB atlas using Node.js driver fails

at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) {
errno: 'ETIMEOUT',
code: 'ETIMEOUT',
syscall: 'queryTxt',
hostname: 'scheduly.1eln0.mongodb.net'
}
I’m facing the above connection Error while connecting with MongoDB Atlas. I’ve double-checked my username and password. I’ve whitelisted all the IP’s. I’m stuck in the middle of a project and cannot connect to the DB itself.
my connection strings are:
const mongoose = require("mongoose");
const mongodb = require("mongodb");
const uri = "mongodb+srv://ghulamghousdev:***********#scheduly.1eln0.mongodb.net/scheduly?retryWrites=true&w=majority
mongoose
.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected");
})
.catch((err) => console.log(err));
The name of the Database on MongoDB atlas is scheduly.
Have you tried to add the ip of your VPS, host to the IP Whitelist of Network access?
You can see more details for that setting from here https://docs.atlas.mongodb.com/security-whitelist/

MongoDB Error: connect ECONNREFUSED 35.156.235.216:27017

trying to connect mongoose to my express app and getting this error:
[nodemon] starting `node index.js`
Listening to the port 5000
connect ECONNREFUSED 35.156.235.216:27017
Im connecting the app directly to MongoDB Atlas, everything was working fine yesterday but this morning i got this Error. Here is the db connection file:
const mongoose = require("mongoose");
require("dotenv").config();
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
console.log("connected to MongoDB..");
} catch (err) {
console.log(err.message);
}
};

Connection Error with MongoDB and Express

Trying to connect my express app with mongodb atlas, but I keep getting this MongodbNetworkError
Server.js file
const express = require("express")
const mongoose = require("mongoose")
const dotenv = require("dotenv")
dotenv.config()
const app = express()
mongoose
.connect(process.env.MONGODB_KEY, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("MongoDB connected"))
.catch(err => console.error(err))
const PORT = process.env.PORT || 5000
app.listen(PORT, () => console.log(`Server running on port ${PORT}`))
Command Line
[nodemon] starting `node server.js`
Server running on port 5000
{ Error: getaddrinfo ENOTFOUND coolcluster-shard-00-00-wqaqv.mongodb.net coolcluster-shard-00-00-
wqaqv.mongodb.net:27017
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
You need to whitelist the IP address of your nodejs server in MongoDB.
After login to the account, Follow the steps
Go to IP Whitelist view.
a)In the Security section of the left navigation, click Network Access. The IP Whitelist tab displays.
b)Click plus icon Add IP Address.
https://docs.atlas.mongodb.com/security-whitelist/#add-whitelist-entries

Node/express application failing to connect to Mongodb Atlas using mongoose

I have a node/express application that I am trying to connect to Mongodb Atlas using mongoose.
All of my code is identical to a previous app that I had connect to Atlas (which worked fine). When I run it on my work machine (Windows 10) everything works as expected. However, when I run it on my MacBook Pro (Mojave), the express app runs but the mongoose connection to Atlas throws the following error:
{ Error: queryTxt EBADNAME development-zv5hp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19)
errno: 'EBADNAME',
code: 'EBADNAME',
syscall: 'queryTxt',
hostname: 'development-zv5hp.mongodb.net' }
server.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
mongoose
.connect(
'mongodb+srv://client:<PASSWORD>#development-zv5hp.mongodb.net/shop',
{ useNewUrlParser: true }
)
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
What might be causing this issue?
I have checked the Atlas user and password and have whitelisted my IP (in fact whitelisted all IPs)
Using:
node v10.15.3
express v4.16.4
mongoose v5.5.1
Using Google's DNS server 8.8.8.8 and 8.8.4.4 can resolve this issue
please add autoIndex: false its working for me
mongoose
.connect(
'mongodb+srv://client:<PASSWORD>#development-zv5hp.mongodb.net/shop',
{autoIndex: false, useNewUrlParser: true }
This error is caused because the URI 'mongodb+srv://client:<PASSWORD>#development-zv5hp.mongodb.net/shop' that was passed to connect was unable to be resolved. Your DNS server does not know it and thus cannot resolve an IP. Hence ebadname.
change this like Addison mentioned

MongoError: failed to connect to serve on first connect in mongoDB atlas

My connection code is entered below. I'm trying to connect to the MongoDB atlas free shared cluster and I keep getting an error saying cannot connect to the server in the first time.
const express = require("express");
const app = express();
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.Promise = require('bluebird');
const productRoutes = require("./api/routes/products");
const orderRoutes = require("./api/routes/orders");
mongoose.connect(
"mongodb://username:password6#cluster0-shard-00-00-3xdjv.mongodb.net:27017,cluster0-shard-00-01-3xdjv.mongodb.net:27017,cluster0-shard-00-02-3xdjv.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin",
{
useMongoClient: true
}
) .then(() => { // if all is ok we will be here
return server.start();
})
.catch(err => { // we will not be here...
console.error('App starting error:', err.stack);
process.exit(1);
});
Can someone explain why I keep getting this error:
App starting error:
MongoError: failed to connect to server [cluster0-shard-00-00-3xdjv.mongodb.net:27017] on first connect
[MongoError: getaddrinfo EAI_AGAIN
cluster0-shard-00-00-3xdjv.mongodb.net:27017].....
I had the same problem before I realized that I had set up a network access rule allowing only connections from a certain IP. After deleting that restriction and adding a new rule for allowing all connections from anywhere, the problem was gone
My datasource config is as follows:
"mongodb-atlas": {
"url": "mongodb+srv://dbuser:PaSsWOrd#cluster0-oxxxb.gcp.mongodb.net/test?retryWrites=true&w=majority&authSource=admin",
"name": "mongodb-atlas",
"connector": "mongodb",
"database": "admin"
}

Resources