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/
Related
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 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 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);
}
I can't connect to the mongoDB, this is the error I'm getting each time:
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Server started on port 5000
Server selection timed out after 30000 ms
[nodemon] app crashed - waiting for file changes before starting...
Already tried:
- changing ip access on mongoDB from everywhere to current ip adress and otherwise,
- creating new account that was for sure made on my current ip adress,
- disabling firewall,
- checked code for errors,
- tried restarting my pc for some reason
here is my code
//////server.js/////
const express = require('express');
const connectDB = require('./config/db');
const app = express();
// Connect Database
connectDB();
app.get('/', (req, res) =>
res.json({ mgs: 'Welcome to the ContactKeeper API...' })
);
// Define Routes
app.use('/api/users', require('./routes/users'));
app.use('/api/auth', require('./routes/auth'));
app.use('/api/contacts', require('./routes/contacts'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
//////default.json/////
{
"mongoURI": "mongodb+srv://artur123:<artur123>#contactkeeper-lv2py.mongodb.net/test?retryWrites=true&w=majority"
}
//////db.js/////
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = () => {
mongoose
.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB Connected'))
.catch(err => {
console.error(err.message);
process.exit(1);
});
};
module.exports = connectDB;
You just have to add your ip in the ip whitelist on mongoDB Atlas under :
Network Access
then restart.
I am testing my app on localhost and using mongdb to connect to a database. I was receiving this error:
UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:27017
I figured out how to reconnect by going into Services and manually starting MongoDB.
However, after researching, I found that my code is not handling the error catching properly. I am not sure how to restructure my code (using .catch() I believe?) to fix this.
Would appreciate any suggestions to help fix and will be great to be able to learn how to do so.
Thanks in advance!
const express = require('express');
const validate = require('./validate.js');
const mongoose = require('mongoose');
const moviesRouter = require('./routes/movies.js');
const app = express();
const PORT = process.env.PORT || 3000;
const DATABASE_URL = process.env.DATABASE_URL ||
'mongodb://localhost/movies';
mongoose.connect(DATABASE_URL, { useNewUrlParser: true,
useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', error => console.error(error));
db.once('open', () => console.log('Connected to Database'));
app.use(express.json());
app.use('/movies', moviesRouter);
app.listen(PORT, () => console.log(`listening on port: ${PORT}`));
As you suggest, using a catch statement would be one way to handle the connection error:
mongoose.connect(DATABASE_URL, { useNewUrlParser: true,
useUnifiedTopology: true }).catch(error => console.error(error));
If an error happens during connection the error will be handled and returned. More info here: https://mongoosejs.com/docs/connections.html#error-handling