Trying to connect cluster to application - mongodb

Im getting this error when I'm connecting my MongoDB Atlas cluster to my application and I am not sure what how to fix this issue as I have whitelisted all IP addresses as well. The code and the error are shown below:
const express = require("express");
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());`
mongoose.connect('mongodb+srv://surpol:mypassword123#cluster0.kiwls.mongodb.net/mydb123?retryWrites=true&w=majority', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
.then(() => console.log('DB Connected!'))
.catch(err => {
console.log(err);
});
MongooseServerSelectionError: connection <monitor> to 54.156.90.92:27017 timed out
at NativeConnection.Connection.openUri (/Users/suryapolina/Documents/GitHub/Phaseify/backend/node_modules/mongoose/lib/connection.js:828:32)
at Mongoose.connect (/Users/suryapolina/Documents/GitHub/Phaseify/backend/node_modules/mongoose/lib/index.js:335:15)
at Object.<anonymous> (/Users/suryapolina/Documents/GitHub/Phaseify/backend/server.js:15:10)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11 {
message: 'connection <monitor> to 54.156.90.92:27017 timed out',
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: 'atlas-wpf52v-shard-0',
maxSetVersion: null,
maxElectionId: null,
servers: Map {
'cluster0-shard-00-00.kiwls.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-01.kiwls.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-02.kiwls.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: 30,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: 8
}
}

Related

Can't connect to mongoose/mongodb

When I'm trying to add an item to my database I get the following error on the terminal:
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at Connection.openUri (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\connection.js:825:32)
at C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\index.js:417:10
at C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\index.js:1270:10)
at Mongoose.connect (C:\Users\88cro\Desktop\blog\node_modules\mongoose\lib\index.js:416:20)
at Object.<anonymous> (C:\Users\88cro\Desktop\blog\server.js:6:10)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 162133351,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\88cro\Desktop\blog\node_modules\mongodb\lib\cmap\connect.js:387:20)
at Socket.<anonymous> (C:\Users\88cro\Desktop\blog\node_modules\mongodb\lib\cmap\connect.js:310:22)
at Object.onceWrapper (node:events:628:26)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
cause: Error: connect ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1284:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}
Node.js v19.0.1
[nodemon] app crashed - waiting for file changes before starting...
I have MongoDB Atlas and mongoshell installed and running but that doesn't seem to fix the problem.
This is how I setup express and mongoose, I tried to change the url in mongoose.connect but it doesn't seem to work
const express = require('express')
const mongoose = require('mongoose')
const articleRouter = require('./routes/articles')
const app = express()
mongoose.connect('mongodb://localhost/blog', {useNewUrlParser: true})
app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: false }))
app.get('/', (req, res) => {
const articles = [{
title: 'Test title',
createdAt: new Date(),
description: 'Test description'
}]
res.render('articles/index', { articles: articles })
})
app.use('/articles', articleRouter)
app.listen(5000)
Any ideas about how to fix this? Thanks!

how to fix the error no. -4078, in mongoose connection to the server what's cause this?

What is wrong with this setup
'''
nodejs
'''
require('dotenv').config()
// console.log(process.env)
const express = require('express')
const app = express()
const expressLayouts = require("express-ejs-layouts")
const indexRouter = require('./routes/index')
const mongoose = require('mongoose');
app.set("view engine", "ejs")
app.set("views", __dirname + "/views")
app.set('layout', "layouts/layout")
app.use(expressLayouts)
app.use(express.static('public'))
app.use('/', indexRouter)
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://localhost:27017/printshop',{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
const db = mongoose.connection
db.on('error', error=> console.log(error))
db.once('open', ()=> console.log('connected to mongogoose'))
app.listen(process.env.PORT)
im trying to connect to mongodb in my local network but suddenly this
error message
just out
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at Connection.openUri (E:\nodejs\node-server\node_modules\mongoose\lib\connection.js:825:32)
at E:\nodejs\node-server\node_modules\mongoose\lib\index.js:417:10
at E:\nodejs\node-server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (E:\nodejs\node-server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (E:\nodejs\node-server\node_modules\mongoose\lib\index.js:1270:10)
at Mongoose.connect (E:\nodejs\node-server\node_modules\mongoose\lib\index.js:416:20)
at Object.<anonymous> (E:\nodejs\node-server\server.js:20:10)
at Module._compile (node:internal/modules/cjs/loader:1112:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1166:10) {
reason: TopologyDescription {
queues:82:21) {
cause: Error: connect ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1237:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
what the mean?
im looking for the log of "connected to mongogoose" but it doesnt show in console then the error comes
ECONNREFUSED ::1:27017
what is this mean?
if anyone had a problem like this you can fix it by changing the
mongoodb://localhost/
to
mongoodb://127.0.0.1/

MongoServerError: bad auth :Authentication Failed

Geeting This Error
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#cluster0.agq2x.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });

how to use connect-mongo version 4x with express-session. I'm getting errors

I am getting errors while trying to save sessions on MongoDB
const MongoStore = require('connect-mongo');
const connectDB = require('./config/db');
const { connection } = require('mongoose');
app.use(
session({
secret: 'some secret',
resave: false,
saveUninitialized: true,
store: MongoStore.create({
client: connection,
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24,
},
})
);
Error:
C:\Users\Tezz\Desktop\Express\PassportJsAuth\express-session-authenticator\node_modules\connect-mongo\build\main\lib\MongoStore.js:126
.db(options.dbName)
^
TypeError: con.db is not a function
at C:\Users\Tezz\Desktop\Express\PassportJsAuth\express-session-authenticator\node_modules\connect-mongo\build\main\lib\MongoStore.js:126:18
Here is the Solution:
const express = require('express');
const session = require('express-session');
require('dotenv').config();
const MongoStore = require('connect-mongo');
const connectDB = require('./config/db');
const PORT = process.env.PORT || 3001;
const MONGO_URI = process.env.MONGODB;
const app = express();
//connectDB should return the client conn.connection.getClient();
const client = connectDB().then((mClient) => {
app.listen(PORT, () => console.log('Server running...');
return mClient;
}).catch(err => console.log(err));
app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use(
session({
secret: 'some-secret',
resave: false,
saveUninitialized: true,
store: MongoStore.create({
client,
}),
})
);
app.get('/', (req, res, next) => {
res.send('<h1>Hello World (sessions)</h1>');
});
```

Can't provoke MongoError - bad auth

Just to be clear, I want to get MongoError bad auth Authentication failed from MongoDB Atlas.
This is about wrong DB password and I'm trying to catch that error and act accordingly.
this is my connection method:
mongoose
.connect(CRED, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => {
console.log('connected to database');
});
and here I'm catching unhandledRejection error that supposed to catch wrong auth:
process.on('unhandledRejection', err => {
console.log(err.name, err.message);
server.close(() => {
process.exit(1);
});
});
If I put correct password, everything works fine and I'm connected to database.
But if I put wrong password, after 30 sec of waiting I get:
MongooseTimeoutError Server selection timed out after 30000 ms
...and this shouldn't suppose to work like that.
I should get MongoError (bad auth) immediately, on first attempt when app is connecting to MongoDB
...or am I doing something wrong?
It's known issue for Mongoose <=5.7.1 with useUnifiedTopology: true option.
Update your Mongoose to 5.9.2 to fix the issue.
With new version, Mongoose fails corectly:
MongooseServerSelectionError MongooseError [MongooseServerSelectionError]: Authentication failed.
at new MongooseServerSelectionError (D:\myapp\node_modules\mongoose\lib\error\serverSelection.js:22:11)
at NativeConnection.Connection.openUri (D:\myapp\node_modules\mongoose\lib\connection.js:808:32)
at Mongoose.connect (D:\myapp\node_modules\mongoose\lib\index.js:333:15)
at Object.<anonymous> (D:\myapp\app.js:46:10)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11 {
message: 'Authentication failed.',
name: 'MongooseServerSelectionError',
reason: TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
},
[Symbol(mongoErrorContextSymbol)]: {}
}
Also, add .catch clause to your code
mongoose
.connect(CRED, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => {
console.log('connected to database');
})
.catch(error => {
//MongooseServerSelectionError MongooseError [MongooseServerSelectionError]: Authentication failed
console.log("Error", error)
});