I'm new to nodeJS, I'm currently following a tutorial on youtube. I have set up my connection string:
const mongoose = require("mongoose");
const connectionString =
"mongodb+srv://mikeyxx:ntpassword#nodeexpressprojects.lm1wpuv.mongodb.net/?retryWrites=true&w=majority";
mongoose
.connect(connectionString)
.then(() => console.log("CONNECTED TO THE DB..."))
.catch((err) => console.log(`Got an error: ${err}`));
But when I lunch my node app. I get this error:
(node:25416) 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.
(Use `node --trace-deprecation ...` to show where the warning was created)
server is listening on port: 5000...
(node:25416) [MONGODB DRIVER] Warning: Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.
(node:25416) [MONGODB DRIVER] Warning: 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.
Got an error: MongoNetworkError: failed to connect to server [ac-99ygtmu-shard-00-02.lm1wpuv.mongodb.net:27017] on first connect [MongoNetworkTimeoutError: connection timed out
at connectionFailureError (C:\Users\USER\Desktop\Backend\node-express-course\03-task-manager\starter\node_modules\mongodb\lib\core\connection\connect.js:362:14)
at TLSSocket.<anonymous> (C:\Users\USER\Desktop\Backend\node-express-course\03-task-manager\starter\node_modules\mongodb\lib\core\connection\connect.js:330:16)
at Object.onceWrapper (node:events:627:28)
at TLSSocket.emit (node:events:513:28)
at Socket._onTimeout (node:net:562:8)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)]
When I run npm start, I expected to get: CONNECTED TO THE DB... but instead I get an error
This is the first time I use MongoDB Atlas to work with Mongo, and while trying to connect, that's the error I get:
Error: connect ECONNREFUSED 3.209.60.172:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1054:14) {
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {}
}
This is my code:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
mongoose.connect('mongodb+srv://johnnybox:<password>#cluster0-cgxqx.mongodb.net/test?retryWrites=true&w=majority', {
useNewUrlParser: true
}).then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(require('./routes'));
app.listen(3331);
ps* I'm not missing my credentials
Already looked for a solution here but there's nothing similar to my problem.
My whitelist:
try this
mongoose
.connect(
'mongodb+srv://{my_user}:{mypass}#johnnybox-cgxqx.mongodb.net/johnnybox?retryWrites=true&w=majority',
{ useNewUrlParser: true }
)
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
Try adding your IP Address in the mongo atlas IP Whitelist.
Otherwise accept every connections if you don't need secure connection.
A new answer to the new error:
According to this answer, which had the same exact error, that is:
'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]:
Add your current IP to whiteList following "clusters/security/whitelist" in MongoDB website.
I'm sorry, I spent at least an hour to solve this. That's all I can do.
Old answer addressing the former error (he fixed this part, but still got a new error):
If you read the error log carefully it says:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block
That means you needed to add catch() to your mongoose connection:
mongoose.connect({some code}).then({some code}).catch(err => console.log(err))
I tried to run this code at home and it worked perfectly!
So it was something here in my office, after some testing, the problem was with the connection port that was locked.
Take a look:
Error: connect ECONNREFUSED 3.209.60.172:27017
Note that it connects to the port 27017
**The Ip is random, so it changes after every requisition.
After my Sd opened this port, everything worked properly!!
Thanks so much for your help guys!
For those of you who tried various URIs the only thing that got it working here is to Add you IP vs allow the access from anywhere. Hope that saves you some time.
I am new to MongoDB 4.0.6 and tried to implement it into my website using Node/Express.js, but when I try to connect to mongodb+srv://${process.env.MONGOUSER}:${process.env.MONGOPASS}#main-03xkr.mongodb.net/main I'm getting this error:
{ Error: querySrv EREFUSED _mongodb._tcp.main-03xkr.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:199:19)
errno: 'EREFUSED',
code: 'EREFUSED',
syscall: 'querySrv',
hostname: '_mongodb._tcp.main-03xkr.mongodb.net' }
I've tried connecting to mongodb://localhost:27017/main, but this does seem work.
Here is the relevant code:
require('dotenv').config();
const mongoose = require('mongoose');
// Database
const uri = `mongodb+srv://${process.env.MONGOUSER}:${process.env.MONGOPASS}#main-03xkr.mongodb.net/main`;
const localURI = 'mongodb://localhost:27017/main';
var Project = require('./models/project');
mongoose.connect(uri, { useNewUrlParser: true });
const db = mongoose.connection;
db.once('open', () => console.log('Successfully connected to MongoDB'));
db.on('error', (e) => console.log(e));
// Routes
app.get('/', (req, res) => {
Project.find({}, (e, projects) => {
if (e) console.log(e);
res.render('home.ejs', {
projects: projects
});
});
});
So does anyone know how to fix this error and maybe explain what is happening here?
If you're encountering this error try to use the older connection string for Node.js 2.2.12 or later:
mongodb://<username>:<password>#main-shard-00-00-03xkr.mongodb.net:27017,main-shard-00-01-03xkr.mongodb.net:27017,main-shard-00-02-03xkr.mongodb.net:27017/main?ssl=true&replicaSet=Main-shard-0&authSource=admin&retryWrites=true
According to MongoDB, SRV is possibly not working due to Mongoose.
I had this same error when I was connecting with Node version 3.0 or later and I resolved it by downgrading to 2.2.12 or later version:
In my case, it's mainly a DNS issue in mac, to resolve it, just add google DNS server under the DNS section in mac book pro settings:
8.8.8.8
4.4.4.4
This error occurs sometimes when you are using MongoDB Atlas and lost your internet connectivity. You will not be able to access your database.
Make sure to change the node version to 2.2.12:
And add IP address:
Pass option { useNewUrlParser: true, useUnifiedTopology: true } to the MongoClient constructor
const uri = "mongodb+srv://${process.env.MONGOUSER}:${process.env.MONGOPASS}#main-03xkr.mongodb.net/main"
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
.catch(error => console.log(error));
You have undefined in your connection string. I don't know if this is typo or not. But try changing
const uri = `mongodb+srv://undefined:${process.env.MONGOPASS}#main-03xkr.mongodb.net/main`;
to
const uri = `mongodb+srv://${process.env.MONGOUSER}:${process.env.MONGOPASS}#main-03xkr.mongodb.net/main`;
I use MongoAtlas for a project and that string (minus the undefined user) looks correct.
In our case antivirus/firewall is blocking,
Try to disable antivirus/firewall and check again. hope it will work.
Error: querySrv ESERVFAIL _mongodb._tcp.databasename-zcbag.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:202:19) {
errno: 'ESERVFAIL',
code: 'ESERVFAIL',
syscall: 'querySrv',
hostname: '_mongodb._tcp.databasename-zcbag.mongodb.net'
}
If the above code is your output then there is no error in your code. You have to check your network connection. Maybe you have to switch your network from the phone network to another or vice versa.
MongoClient.connect(
"mongodb://USER:PASSWORT#mflix-shard-00-00-r5yfb.mongodb.net/test?ssl=true&replicaSet=mflix-shard-0&authSource=admin&retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true },
)
.catch(err => {
console.error(err.stack)
process.exit(1)
})
.then(async client => {
await MoviesDAO.injectDB(client)
await UsersDAO.injectDB(client)
await CommentsDAO.injectDB(client)
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
})
Maybe can works with MongoClient( not Mongoose )
In my case it was throwing this error due mongodb cluster auto paused because of prolonged inactivity. I just resumed it, then it started properly.
In my case, this error was happening when the DNS configuration in my TP-Link Router was missing.
I've installed OpenWRT firmware on it and forgot to adjust DNS settings.
I was able to open YouTube or any other website because that's not my main router, but could not connect to database.
It was an internet issue, like #Kamesh Kumar Singh said in his answer.
I think that this is not an usual answer for this question, but may help someone.
This error occurs if you are not able to connect to mongoDB Atlas database. Your server runs successfully but you get this error while connecting to database. Make sure your internet connection is good and try again you won't see this error.
I solved mine by going into the MongoDB -> login -> databases -> connect -> connect your application (middle one) -> copy the code -> paste the code into the mongooseDB code in my .JS file:
const mongoose = require('mongoose');
require('dotenv/config');
mongoose
.connect(process.env.THE_MONGO_DB_URL_GOES_HERE_IN_DOTENV_FILE, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => console.log("Database connected!"))
.catch(err => console.log(err));
const PostSchema = mongoose.Schema({
email: String,
password: String
}, {strict: false});
const DataEntry = mongoose.model('n26-users-collection', PostSchema);
module.exports = DataEntry;
"Not in the root folder" scenario:
Create a .env file in the root directory of your project. https://github.com/motdotla/dotenv
One scenario for this error is to create dotenv .env file --NOT-- in the root folder (Under /src for example).
Than this code:
const url = `mongodb+srv://${process.env.DB_USER}:${
process.env.DB_USER_PASSWORD
}#${process.env.DB_CLUSTER}.mongodb.net`;
console.log(url)
output:
mongodb+srv://undefined:undefined#undefined.mongodb.net
So the "undefined" URL connection:
const client = new MongoClient(url);
Throw 3 warnings:
(node:27240) UnhandledPromiseRejectionWarning: Error: querySrv
ENOTFOUND _mongodb._tcp.undefined.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:207:19)
(node:27240) 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:27240) [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.
One more "close" scenario:
.env in the root folder but the file is empty:
Solution
The first step to solve this issue is to console.log(url) and check if process.env returns the correct Connection String.
Related:
dotenv github readme: https://github.com/motdotla/dotenv#readme
Connect to a MongoDB Database Using Node.js
: https://developer.mongodb.com/quickstart/node-connect-mongodb/
In my case, the issue occurred because MongoDB paused my cluster due to over 4 months of inactivity. After I logged in to my account and resumed the activity of the cluster, the issue was immediately resolved.
I am getting the error message deprecated body-parser i've looked up other methods concerning parsing the data but none seem to work. the below code what ive got
const express = require('express');
const app = express();
const Task = require('./api/models/ListModels.js'); //created model loading here
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Tododb');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const routes = require('./api/routes/ListRoutes.js'); //importing route
routes(app); //register the route
app.listen(3000, () => {
console.log('running on 3000')
})
The error:
PS C:\Users\demar\Desktop\New folder\ListAPI> node app.js
(node:10424) 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.
running on 3000
(node:10424) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (C:\Users\demar\Desktop\New folder\ListAPI\node_modules\mongodb-core\lib\topologies\server.js:562:11)
at emitOne (events.js:116:13)
at Pool.emit (events.js:211:7)
at Connection.<anonymous> (C:\Users\demar\Desktop\New folder\ListAPI\node_modules\mongodb-core\lib\connection\pool.js:316:12)
at Object.onceWrapper (events.js:317:30)
at emitTwo (events.js:126:13)
at Connection.emit (events.js:214:7)
at Socket.<anonymous> (C:\Users\demar\Desktop\New folder\ListAPI\node_modules\mongodb-core\lib\connection\connection.js:245:50)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
(node:10424) 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(). (rejection id: 1)
(node:10424) [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.
It honestly tells you what to do..
To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
I added the options and it works perfectly..
Originally:
// Connect to Mongo:
mongoose.connect(db).then(() => console.log("Mongo DB Connected")).catch(err => console.log(err));
Current:
// Connect to Mongo:
mongoose.connect(db, { useNewUrlParser: true}).then(() => console.log("Mongo DB Connected")).catch(err => console.log(err));
This fixed the issue
The error is that your version of Node's URL string parser, that Mongoose is using, is deprecated.
Pass in the option {useNewUrlParser: true} to mongoose.connect() to use the new Node Core URL API.
mongoose.connect('mongodb://localhost/Tododb', {useNewUrlParser: true})
That error is appearing because you didn't specified the port number mongodb is running on.
mongoose.connect('mongodb://localhost:27017/databasename', { useNewUrlParser: true })
this will fix your issue :)
Yes, body-parser has been deprecated.
Don't use it anymore
Since Express 4.16+ the body parsing functionality has become built into express
You can do
app.use(express.urlencoded({extended: true}));
app.use(express.json()) // To parse the incoming requests with JSON payloads
From directly express, without having to install body-parser.
so you can uninstall body-parser using npm uninstall body-parser, and simply use the above code from express.
I am trying to use connect-mongo to store my express-session's however I am getting a depreciation warning on my server, but not my development machine.
The server is running Ubuntu 16.04, node v8.9.3
My dev machine is windows, node v8.9.4
the codebase is identicle. however on my server I am getting the following messages:
(node:1789) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: cyclic dependency detected
(node:1789) [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.
I admit I am a novice when it comes to node.
this is the code I am using:
const express = require('express');
const path = require('path');
const expressSession = require('express-session');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(expressSession);
//Custom Modules Declarations
const settings = require('./config/app-settings');
//Open Connection to MongoDB
const connection = mongoose.createConnection(settings.settings.databaseUri);
//App Setup
const app = express();
// Express session
app.use(expressSession({
secret: 'secret',
//cookie: {maxAge: config.mongoDBSessionMaxAge * 1000},
resave: true,
saveUninitialized: true,
store: new MongoStore({
mongooseConnection: connection,
clear_interval: settings.settings.mongoDBSessionMaxAge
})
}));
please could you help me to remove the errors?