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);
}
Related
I keep getting this error although I have allowed access from anywhere in the Network access section of the cluster. (Screenshot of the same is attached below)
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: https://docs.atlas.mongodb.com/security-whitelist/
at NativeConnection.Connection.openUri (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/connection.js:824:32)
at /home/runner/store-cipher-backend-1/node_modules/mongoose/lib/index.js:380:10
at /home/runner/store-cipher-backend-1/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/index.js:1225:10)
at Mongoose.connect (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/index.js:379:20)
at intialDbConnection (/home/runner/store-cipher-backend-1/db/db.connect.js:5:20)
at Object.<anonymous> (/home/runner/store-cipher-backend-1/index.js:15:1) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'cluster0-shard-00-00.fkvic.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-01.fkvic.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-02.fkvic.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-on2j4f-shard-0',
logicalSessionTimeoutMinutes: undefined
},
code: undefined
}
Here is the connection code
const mongoose = require('mongoose');
const mySecret = process.env['mongoUrl']
const intialDbConnection = async () => {
try {
await mongoose.connect(mySecret, {
useNewUrlParser: true,
useUnifiedTopology: true
})
console.log("db connected")
}
catch (error) {
console.error(error);
}
}
module.exports = { intialDbConnection }
And the entire code is here https://replit.com/#KumaraswamyA/store-cipher-backend-1
Access from anywhere mongodb access management
If you are looking for an answer follow this thread. mongoDB community support
The MongoDB community has made it clear that the error is not from their end.
and after reaching out to Replit. They responded that they are aware of the issue and have provided a temporary solution:
“You can run “kill 1” in the shell of your Repl which will reboot it and may fix the issue, although it isn’t a 100% reliable workaround.”
Apart from this the solution that has worked for me is changing the file name and running, the DB gets connected. In case you have already used the APIs in the frontend, after doing the above step change back your file name to the old one and the DB gets connected without any issues.
Cheers.
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%
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/
I am trying to connect to a cluster created in Mongodb Atlas using mongoose in node js and I am facing below issues when doing so.
When I use the connection string that is given in the Mongo db atlasmongodb+srv://lm_dev_app:<password>#lmdev-q5biw.mongodb.net/test?retryWrites=true&w=majorityI get below error
{ Error: queryTxt EBADNAME lmdev-q5biw.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19)
errno: 'EBADNAME',
code: 'EBADNAME',
syscall: 'queryTxt',
hostname: 'lmdev-q5biw.mongodb.net'}
I cannot use this connection string in Mongodb Compass as well as I am getting the same error there.
If I try to connect using mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net/test i get below error
MongooseServerSelectionError: connection to 54.66.221.230:27017 closed
However I am able to connect to each node using Mongodb Compass which eliminates the possibility of my ipaddress not being whitelisted.
Here is the sample code that I am using
const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net/test", {
useNewUrlParser: true,
useUnifiedTopology: true,
replicaSet: "LMDEV"
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
Any thoughts on what is happening here.
There are couple of things that I need to highlight here.
The default connection string that is shown in Mongodb Atlas seems to be wrong. It shows you mongodb+srv://<username>:<password>#<cluster_url>/test?retryWrites=true&w=majority. But I used mongodb://<username>:<password>#<node_url>:27017/ to make it work. You can also use mongodb://<username>:<password>#<node_url>:27017/admin.
Pass ssl:true in the options that we are passing.
Finally one of the 3 options can be used to connect to the database.
a. const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net:27017/", {
useNewUrlParser: true,
useUnifiedTopology: true,
authSource:"admin",
ssl: true,
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
b. const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net:27017/", {
useNewUrlParser: true,
useUnifiedTopology: true,
authSource:"admin",
ssl: true,
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
c. const mongoosePromise = mongoose.connect("mongodb://lm_dev_app:<password>#lmdev-shard-00-01-q5biw.mongodb.net:27017/admin", {
useNewUrlParser: true,
useUnifiedTopology: true,
ssl: true,
}, (err) => {
if (err) {
console.log(err);
} else {
console.log("Successful");
}
});
EDIT 1:
After having a chat with Atlas support team I was told that issue in point 1 is due to DNS resolution issue with my service provider. So i have changed my DNS settings to point to a public DNS server.
After trying different connection strings for several hours, I finally just copy/pasted the connection string from MongoDB Compass and it works! (first connect, then edit the connection string as it will change)
It looks like this:
mongodb+srv://username:password#fra-atlas-shard.abcde.mongodb.net/test?authSource=admin&replicaSet=atlas-abcde-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true
I'm trying to using sails-arangodb to connect sails to arangodb. I follow this guide: Arangodb use case guide to connect to arangodb. But i face error:
error: Error: The hook `orm` is taking too long to load. Make sure it
is triggering its `initialize()` callback, or else set `sails.conf
g.orm._hookTimeout to a higher value (currently 20000)
at Timeout.tooLong [as _onTimeout] (C:\Users\thanhtv\AppData\Roaming\npm\no
e_modules\sails\lib\app\private\loadHooks.js:85:21)
at ontimeout (timers.js:475:11)
at tryOnTimeout (timers.js:310:5)
at Timer.listOnTimeout (timers.js:270:5)
here is my connections.js
module.exports.connections = {
localArangoDB: {
adapter: 'sails-arangodb',
host: '192.168.0.152',
port: 8529,
// user: 'root',
// password: 'root',
database: {
name: 'test',
graph: 'test'
}
// database: 'test',
//
// graph: 'test', // ArangoDB specific
// collection: 'test', // ArangoDB specific
},
};
and here is my models.js
module.exports.models = {
connection: 'localArangoDB',
migrate: 'alter'
};
I'm i missing something ?