Mongodb issues connecting - mongodb

I'm trying to connect in to my DATA Base using Mongoose here is my code:
mongoose
.connect(process.env.MONGODB_URL)
.then(() => {
console.log("connected to MongoDB!");
})
.catch((err) => {
console.log(err);
});
Expecting from console.log( "connected to MongoDB!"); but instead i get this :
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
server started by me
/subscribers
Error: querySrv ETIMEOUT _mongodb._tcp.subscribers-app.nrro0mj.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:internal/dns/promises:251:17) {
errno: undefined,
code: 'ETIMEOUT',
syscall: 'querySrv',
hostname: '_mongodb._tcp.subscribers-app.nrro0mj.mongodb.net'
}

The problem was in my router
solutions:
Restart your Router.
Manually Set your DNS Server.

Related

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 in mac [duplicate]

I've been trying for over 2 hours now trying to figure out what's wrong with this database. I've tried everything. From reinstalling the server, restarting the processes, rebooting and so much more. It keeps giving me this error when trying to connect:
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (D:\TheShed\MX_\node_modules\mongoose\lib\connection.js:797:32)
at D:\TheShed\MX_\node_modules\mongoose\lib\index.js:330:10
at D:\TheShed\MX_\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (D:\TheShed\MX_\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (D:\TheShed\MX_\node_modules\mongoose\lib\index.js:1151:10)
at Mongoose.connect (D:\TheShed\MX_\node_modules\mongoose\lib\index.js:329:20)
at module.exports (D:\TheShed\MX_\other\DB\mong.js:4:20)
at D:\TheShed\MX_\app.js:195:37
at Object.<anonymous> (D:\TheShed\MX_\app.js:197:3) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 1421094,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (D:\TheShed\MX_\node_modules\mongodb\lib\cmap\connect.js:293:20)
at Socket.<anonymous> (D:\TheShed\MX_\node_modules\mongodb\lib\cmap\connect.js:267:22)
at Object.onceWrapper (node:events:510:26)
at Socket.emit (node:events:390:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
This error wont resolve no matter what I do. The MongoDB server is running, I've checked by doing >show dbs and it lists them perfectly fine. Also, C:/data/db exists and its fine too.
What do I do?
Here's my connection code:
(async () => {
await require('./other/DB/mong')();
console.log("Connected to Database.");
})();
and here's ./other/DB/mong:
var mongoose = require("mongoose");
module.exports = async () => {
await mongoose.connect('mongodb://localhost:27017/MX', {
keepAlive: true,
useNewUrlParser: true,
useUnifiedTopology: true
});
return mongoose;
}
I just found a solution in the internet ,
If you are using latest nodejs (v17.x) , then try updating mongodb url from localhost to 127.0.0.1
This worked for me :slightly_smiling_face:
Updated my mongodb url from 'mongodb://localhost:27017/student' to 'mongodb://127.0.0.1:27017/student' and it worked fine for me
MongoDB does not bind to localhost on ipv6 by default.
If you want it to listen on ::1 you will need to enable net.ipv6 and either enable net.bindIpAll or explicitly list the loopback address in net.bindIp
update from
'mongodb://localhost:27017/myapp' to
'mongodb://127.0.0.1:27017:27017/myapp'
then check to be sure it connects.
mongoose
.connect(process.env.DATABASE, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('DB Connected'));
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
autoIndex: false, // Don't build indexes
maxPoolSize: 10, // Maintain up to 10 socket connections
serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
family: 4 // Use IPv4, skip trying IPv6
}
use mongoose.connect("mongodb://127.0.0.1:27017/databasename"); instead of localhost
just change this, mongoose.connect('mongodb://localhost:27017/Database-name');
---> mongoose.connect("mongodb://127.0.0.1:27017/Database-name");
If you are using latest nodejs. If connecting fails on your machine, try using 127.0.0.1 instead of localhost like
mongoose.connect('mongodb://127.0.0.1:27017/myapp');
you can also use mongodb://0.0.0.0:27017/database_name
step 1. check MongoDB service is running -> if OK.
try next:
step 2. replace 127.0.0.1 from localhost -> this should work 100%

Mongoose Connection Error in Stackblitz - Mean app

I am trying to create a mean app. I am receiving errors while connecting mean app with MongoDb using mongoose. I am using "express": "^4.17.1", and "mongoose": "^6.0.7".
const mongoose = require('mongoose');
// Connecting to MongoDb
mongoose.connect(
'mongodb+srv://MongoDb:<password>#cluster0.xfdie.mongodb.net/myFirstDatabase?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
// On Connection
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDb');
});
mongoose.connection.on('error', (err) => {
if (err) {
console.log('Error in MongoDb Connection' + err);
}
});
It's working fine with the localhost but I am receiving the following error in Stackblitz.
Error in MongoDb ConnectionTypeError: this._handle[e] is not a function
(node:13) UnhandledPromiseRejectionWarning: TypeError: this._handle[e] is not a function
at Resolver.querySrv [as resolveSrv] (https://file-sharing-portal.jw.staticblitz.com/blitz.fa2fa735bbb029186c23972eb56445ed5c5fdef5.js:6:585119)
at Object.resolveSRVRecord (/home/projects/file-sharing-portal/node_modules/mongodb/lib/connection_string.js:55:9)
at Object.connect (/home/projects/file-sharing-portal/node_modules/mongodb/lib/operations/connect.js:41:36)
at eval (/home/projects/file-sharing-portal/node_modules/mongodb/lib/mongo_client.js:127:23)
at Object.maybePromise (/home/projects/file-sharing-portal/node_modules/mongodb/lib/utils.js:518:5)
at MongoClient.connect (/home/projects/file-sharing-portal/node_modules/mongodb/lib/mongo_client.js:126:24)
at eval (/home/projects/file-sharing-portal/node_modules/mongoose/lib/connection.js:785:12)
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (/home/projects/file-sharing-portal/node_modules/mongoose/lib/connection.js:776:19)
at eval (/home/projects/file-sharing-portal/node_modules/mongoose/lib/index.js:328:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:13) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Please assist.
I asked for help in stackblitz-help channel in discord for the same and was informed that Mongoose isn't supported yet : https://github.com/stackblitz/core/issues/251
const mongoose = require('mongoose');
const app = express();
mongoose.Promise = global.Promise;
mongoose.connect("CONNECTION_STRING", "OPTIONS", (error) => {
if (error)
console.log("Connection error - ", error);
else
console.log("MongoDB connection established");
});
let server = http.createServer(app);
server.setTimeout(500000);
server.listen(3000);
try with above code snippets

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 + promise error

I'm just getting started with MongoDB. After installing it and running the code I'm getting an error.
Code:
mongoose.connect('mongodb://localhost:27017/yelp-camp', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", ()=> {
console.log("Database connected");
});
Error:
First part of error
Second part of error
ECONNREFUSED usually means that your services isn't available. Is seems to me that your mongodb isn't running or is listening on a different port
Maybe try port 27018 or 27019
https://docs.mongodb.com/manual/reference/default-mongodb-port/

Why mongoose is not connecting to MongoDB Atlas?

I am trying to connect to MongoDB Atlas But I am getting this error
(node:7191) 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.
{ MongoError: no mongos proxy available
at Timeout.<anonymous> (/home/gaurav/Downloads/Assignments/DevConnection_2.0/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/mongos.js:739:28)
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5) name: 'MongoError', [Symbol(mongoErrorContextSymbol)]: {} }
I am trying to connect like this
db = "mongodb+srv://<username>:<password>#devconnector-sk8na.mongodb.net/test?retryWrites=true&w=majority"
try{
await mongoose.connect(db, { useNewUrlParser: true})
console.log("MongoDB Connected..")
} catch(err){
console.error(err);
process.exit(1);
}
I also replaced username and password while using it.
I should get this output -
MongoDB connected...
I am using,
"mongoose": "^5.8.1",
Even if I downgrade to Mongoose version 5.6.13, Deprecation warning goes away but still the following error persists -
{ MongoError: no mongos proxy available
at Timeout.<anonymous> (/home/gaurav/Downloads/Assignments/DevConnection_2.0/node_modules/mongodb-core/lib/topologies/mongos.js:736:28)
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5) name: 'MongoError', [Symbol(mongoErrorContextSymbol)]: {} }
Without downgrading,
Can you add this line next to useNewUrlParser:true and then run again?
useUnifiedTopology: true
Your code should look like this
db = "mongodb+srv://<username>:<password>#devconnector-sk8na.mongodb.net/test?retryWrites=true&w=majority"
try{
await mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
console.log("MongoDB Connected..")
} catch(err){
console.error(err);
process.exit(1);
}

Mongodb Atlas Express.js Error: getaddrinfo ENOTFOUND

I want to connect my express app to my mongoDb Atlas cluster.I'm from Iran, and cloud databases are sanctioned for us. I used VPN to bypass it in order to be able to practice.
Is there some coding mistake that I've done or is it because of using VPN?
The error:
(node:9008) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
connected
events.js:174
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND
is listening...
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
Emitted 'error' event at:
at GetAddrInfoReqWrap.doListen [as callback] (net.js:1448:12)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:17)
[nodemon] app crashed - waiting for file changes before starting...
And the code:
database.js
----------------
const mongoDb = require('mongodb');
const MongoClient = mongoDb.MongoClient;
let _db;
const mongoConnect = callback => {
MongoClient.connect(
'mongodb+srv://<someUser>:<somePassword>#<someCluster>-zh1eb.mongodb.net/test?retryWrites=true'
)
.then(client => {
console.log('\nconnected\n');
_db = client.db();
callback();
})
.catch(err => {
console.log('\nerror\n', err);
throw err;
});
};
const getDb = () => {
if (_db) {
return _db;
}
throw 'NO DATABASE FOUND';
};
exports.mongoConnect = mongoConnect;
exports.getDb = getDb;
app.js
------------
...
const mongoConnect = require('./util/database').mongoConnect;
...
mongoConnect(() => {
app.listen(3000, '\nis listening...\n');
});
I found out what was the problem:
mongoConnect(() => {
app.listen(3000, '\nis listening...\n');
});
should actually be
mongoConnect(() => {
app.listen(3000, () => { console.log('\nis listening...\n');});
});
Silly me... :)
For those having such issue:
first check out whether the source of problem is your code or the connection to MongoDb.
That is instead of choosing "connect your application" select "connect with Mongodb Compass".
If the Mongodb Compass could connect and show your cluster, then definitely there is something wrong with your code, esp. how it's coded to connect.