1

My application was running just fine and was connected to mongoDB while developing a simple node js application. But suddenly it started showing this error. Here is a snap of the console:

enter image description here

Here is my file providing mongoURI, and it was working just fine before the error:

module.exports = {
  mongoURI:
    "mongodb+srv://glorious:glorious@cluster0-to57n.mongodb.net/test?retryWrites=true&w=majority"
};

Here is my server.js file:

const express = require("express");
const mongoose = require("mongoose");

const app = express();

// DB Config
const db = require("./config/keys").mongoURI;

// Connect to MongoDB
mongoose
  .connect(db)
  .then(() => console.log("MongoDB Connected"))
  .catch(err => console.log(err));

app.get("/", (req, res) => res.send("Hello World"));

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server running on port ${port}`));

And here is my package.json file:

{
  "name": "devconnector",
  "version": "1.0.0",
  "description": "A social network for developers",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "server": "nodemon server.js"
  },
  "author": "Utkarsh Shrivastava",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "gravatar": "^1.8.0",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.7.13",
    "passport": "^0.4.0",
    "passport-jwt": "^4.0.0",
    "validator": "^12.1.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.1"
  }
}
  • Does this answer your question? [Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true](https://stackoverflow.com/questions/50448272/avoid-current-url-string-parser-is-deprecated-warning-by-setting-usenewurlpars) And they have documented usual deprecation warnings [Mongoose deprecations](https://mongoosejs.com/docs/deprecations.html) – ambianBeing Dec 06 '19 at 10:16
  • @ambianBeing directly after the warning there's an ECONNRESET, which indicates that the server is not reachable at that location ... – Jonas Wilms Dec 06 '19 at 10:46
  • Are you able to connect to the cluster instance directly via shell?? `mongo --host mongodb+srv://glorious:glorious@cluster0-to57n.mongodb.net/test?retryWrites=true&w=majority` – ambianBeing Dec 06 '19 at 12:35

4 Answers4

1

useNewUrlParser doc:

The useNewUrlParser Option

By default, mongoose.connect() will print out the below warning:

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.

The MongoDB Node.js driver rewrote the tool it uses to parse MongoDB connection strings. Because this is such a big change, they put the new connection string parser behind a flag. To turn on this option, pass the useNewUrlParser option to mongoose.connect() or mongoose.createConnection().

mongoose.connect(uri, { useNewUrlParser: true });
mongoose.createConnection(uri, { useNewUrlParser: true }); 

You can also set the global useNewUrlParser option to turn on useNewUrlParser for every connection by default.

// Optional. Use this if you create a lot of connections and don't
want // to copy/paste `{ useNewUrlParser: true }`.
mongoose.set('useNewUrlParser', true); 

To test your app with {useNewUrlParser: true }, you only need to check whether your app successfully connects. Once Mongoose has successfully connected, the URL parser is no longer important. If you can't connect with { useNewUrlParser: true }, please open an issue on GitHub.

useUnifiedTopology doc:

useUnifiedTopology

By default, mongoose.connect() will print out the below warning:

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. 

Mongoose 5.7 uses MongoDB driver 3.3.x, which introduced a significant refactor of how it handles monitoring all the servers in a replica set or sharded cluster. In MongoDB parlance, this is known as server discovery and monitoring.

To opt in to using the new topology engine, use the below line:

mongoose.set('useUnifiedTopology', true); 

If you find any unexpected behavior, please open up an issue on GitHub.

So you need to pass both options to mongoose.connect:

// Connect to MongoDB
mongoose
  .connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
  ...
Fraction
  • 11,668
  • 5
  • 28
  • 48
0

your server.js file

const express = require('express');
const connectDB = require('./config/db');
const app = express();
// connect Database
connectDB();
app.get('/', (req, res) => res.send('API Running...'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server Started On Port ${PORT}`));

db.js file under config folder

const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');

const connectDB = async () => {
  try {
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log('MongoDB Connected !!');
  } catch (err) {
    console.error(err.message);
    // Exit process
    process.exit(1);
  }
};

module.exports = connectDB;

default.json under config folder

{
  "mongoURI": mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]
}

you can check more on Connection String URI Format for default.json

Pankaj
  • 29
  • 6
-1

You are missing URL PARSER. Just modify your code to

...rest of the code

// Connect to MongoDB
mongoose
  .connect(db, {newUrlParser: true})
  .then(() => console.log("MongoDB Connected"))
  .catch(err => console.log(err));

...rest of the code

Or you can also set it globally using

mongoose.set('useNewUrlParser', true);

Read more about it here https://mongoosejs.com/docs/deprecations.html

Mr.Bhat
  • 397
  • 5
  • 15
-1

I have Just Worked with Mondo DB. This code may helps

add {useNewUrlParser:true} while connecting to MongoDb.see Mongo DB deprecations

your server.js file:

const express = require("express");
const mongoose = require("mongoose");

const app = express();

// DB Config
const db = require("./config/keys").mongoURI;

// Connect to MongoDB
mongoose
  .connect(db, { useNewUrlParser: true })
  .then(() => console.log("MongoDB Connected"))
  .catch(err => console.log(err));

app.get("/", (req, res) => res.send("Hello World"));

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server running on port ${port}`));

Hope this work fine, and will connect you mongo db.

Prashanth Reddy
  • 749
  • 5
  • 19