278

I have a database wrapper class that establishes a connection to some MongoDB instance:

async connect(connectionString: string): Promise<void> {
        this.client = await MongoClient.connect(connectionString)
        this.db = this.client.db()
}

This gave me a warning:

(node:4833) 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 connect() method accepts a MongoClientOptions instance as second argument. But it doesn't have a property called useNewUrlParser. I also tried to set those property in the connection string like this: mongodb://127.0.0.1/my-db?useNewUrlParser=true but it has no effect on those warning.

So how can I set useNewUrlParser to remove those warning? This is important to me since the script should run as cron and those warnings result in trash-mail spam.

I'm using mongodb driver in version 3.1.0-beta4 with corresponding @types/mongodb package in 3.0.18. Both of them are the latest avaliable using npm install.

Workaround

Using an older version of mongodb driver:

"mongodb": "~3.0.8",
"@types/mongodb": "~3.0.18"
Preview
  • 35,317
  • 10
  • 92
  • 112
Lion
  • 16,606
  • 23
  • 86
  • 148
  • 6
    That's coming from the `beta` version which somehow got released on npm over the weekend. Don't worry about it until the API is actually finalized. You did the right thing installing a stable version. – Neil Lunn May 21 '18 at 11:59
  • 1
    above 3.0.0 of mongodb add simply mongoose.connect("mongodb://localhost:portnumber/YourDB", { useNewUrlParser: true }) – Majedur Jan 05 '19 at 10:03

22 Answers22

447

Check your mongo version:

mongo --version

If you are using version >= 3.1.0, change your mongo connection file to ->

MongoClient.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true })

or your mongoose connection file to ->

mongoose.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true });

Ideally, it's a version 4 feature, but v3.1.0 and above are supporting it too. Check out MongoDB GitHub for details.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abhishek Sinha
  • 5,095
  • 1
  • 15
  • 14
  • 1
    @AbhishekSinha Why with mongo >= 4.0.0? I'm using 3.6.5 and the annoying message has gone too. – greuze Sep 20 '18 at 11:29
  • Yup fixed that. Basically, it's a v4 feature but v3.1.0 and above supports the new feature as well. – Abhishek Sinha Sep 25 '18 at 06:17
  • 3
    This is the best, just wanted to add, if you have a callback, esp for error, just use this: mongoose.connect(dbUrl, { useNewUrlParser: true }, function(err) { console.log("mongoDB connected", err); }) – ptts Nov 28 '18 at 12:16
51

As noted the 3.1.0-beta4 release of the driver got "released into the wild" a little early by the looks of things. The release is part of work in progress to support newer features in the MongoDB 4.0 upcoming release and make some other API changes.

One such change triggering the current warning is the useNewUrlParser option, due to some changes around how passing the connection URI actually works. More on that later.

Until things "settle down", it would probably be advisable to "pin" at least to the minor version for 3.0.x releases:

  "dependencies": {
    "mongodb": "~3.0.8"
  }

That should stop the 3.1.x branch being installed on "fresh" installations to node modules. If you already did install a "latest" release which is the "beta" version, then you should clean up your packages ( and package-lock.json ) and make sure you bump that down to a 3.0.x series release.

As for actually using the "new" connection URI options, the main restriction is to actually include the port on the connection string:

const { MongoClient } = require("mongodb");
const uri = 'mongodb://localhost:27017';  // mongodb://localhost - will fail

(async function() {
  try {

    const client = await MongoClient.connect(uri,{ useNewUrlParser: true });
    // ... anything

    client.close();
  } catch(e) {
    console.error(e)
  }

})()

That's a more "strict" rule in the new code. The main point being that the current code is essentially part of the "node-native-driver" ( npm mongodb ) repository code, and the "new code" actually imports from the mongodb-core library which "underpins" the "public" node driver.

The point of the "option" being added is to "ease" the transition by adding the option to new code so the newer parser ( actually based around url ) is being used in code adding the option and clearing the deprecation warning, and therefore verifying that your connection strings passed in actually comply with what the new parser is expecting.

In future releases the 'legacy' parser would be removed and then the new parser will simply be what is used even without the option. But by that time, it is expected that all existing code had ample opportunity to test their existing connection strings against what the new parser is expecting.

So if you want to start using new driver features as they are released, then use the available beta and subsequent releases and ideally make sure you are providing a connection string which is valid for the new parser by enabling the useNewUrlParser option in MongoClient.connect().

If you don't actually need access to features related to preview of the MongoDB 4.0 release, then pin the version to a 3.0.x series as noted earlier. This will work as documented and "pinning" this ensures that 3.1.x releases are not "updated" over the expected dependency until you actually want to install a stable version.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • 1
    Do you have more information about what you mean when you say "released into the wild"? How did 3.1.0-beta4 escape from the zoo? Can you cite any refs about that? – Wyck Jun 25 '18 at 13:09
  • 2
    @Wyck The "reference" was of course that at the time the question was asked, doing `npm install mongodb` resulting in the **"beta"** ( clearly marked in the version string shown in the question ) being installed since it was marked as `stable` in the npm repository when it should not have been. This was indeed an **error** at the time and should always be considered so if any code release showing `alpha` or `beta` within the version string is similarly marked as stable. Naturally time has passed and this is a feature in stable releases now, until ( as noted ) it will eventually go away. – Neil Lunn Apr 28 '19 at 02:10
47

The below highlighted code to the mongoose connection solved the warning for the mongoose driver:

mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Narendra Maru
  • 787
  • 7
  • 8
  • 5
    not working for me. still getting: (node:35556) 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. – Alex Dec 31 '18 at 18:27
  • You must need to save server.js or app.js wherever you are giving DB path if still not working try by deleting and reinstalling node_modules by entering npm install whenever your package.json file is – Narendra Maru May 28 '19 at 08:11
31

There is nothing to change. Pass only in the connect function {useNewUrlParser: true }.

This will work:

    MongoClient.connect(url, {useNewUrlParser:true,useUnifiedTopology: true }, function(err, db) {
        if(err) {
            console.log(err);
        }
        else {
            console.log('connected to ' + url);
            db.close();
        }
    })
peinearydevelopment
  • 11,042
  • 5
  • 48
  • 76
AAshish jha
  • 952
  • 8
  • 6
23

You just need to set the following things before connecting to the database as below:

const mongoose = require('mongoose');

mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);

mongoose.connect('mongodb://localhost/testaroo');

Also,

Replace update() with updateOne(), updateMany(), or replaceOne()
Replace remove() with deleteOne() or deleteMany().
Replace count() with countDocuments(), unless you want to count how many documents are in the whole collection (no filter).
In the latter case, use estimatedDocumentCount().
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shraddha J
  • 714
  • 9
  • 17
20

You need to add { useNewUrlParser: true } in the mongoose.connect() method.

mongoose.connect('mongodb://localhost:27017/Notification',{ useNewUrlParser: true });
turivishal
  • 34,368
  • 7
  • 36
  • 59
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
16

The connection string format must be mongodb://user:password@host:port/db

For example:

MongoClient.connect('mongodb://user:password@127.0.0.1:27017/yourDB', { useNewUrlParser: true } )
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Boris Traljić
  • 956
  • 1
  • 10
  • 16
10

The following works for me

const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost/playground", { useNewUrlParser: true,useUnifiedTopology: true })
.then(res => console.log('Connected to db'));

The mongoose version is 5.8.10.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Guruprasad
  • 753
  • 6
  • 23
8

The problem can be solved by giving the port number and using this parser: {useNewUrlParser: true}

The solution can be:

mongoose.connect("mongodb://localhost:27017/cat_app", { useNewUrlParser: true });

It solves my problem.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mehedi Abdullah
  • 772
  • 10
  • 13
8

I don't think you need to add { useNewUrlParser: true }.

It's up to you if you want to use the new URL parser already. Eventually the warning will go away when MongoDB switches to their new URL parser.

As specified in Connection String URI Format, you don't need to set the port number.

Just adding { useNewUrlParser: true } is enough.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sam
  • 5,375
  • 2
  • 45
  • 54
  • 1
    I've added the port number and still get the error message. I find the error message very confusing and misleading: why do I get a message telling me to use the new format, when in fact I'm using the old format and it works perfectly...!!?? – Nico Oct 03 '18 at 18:44
  • 2
    Good question! Note that it's a warning. Not an error. Only by adding in `useNewUrlParser: true` will the warning disappear. But that's a bit stupid as this extra parameter will become obsolete once mongo switches to their new url parser. – Sam Oct 04 '18 at 09:49
  • how did you know that the port number is what the new url parser expects? I can't find anything that actually describes what the new url parser is – bluegreen Oct 22 '18 at 19:15
  • @Brad, indeed. I was assuming you needed to add the port number, but the Mongo specs still mention the port number as being optional. I updated my answer accordingly. – Sam Oct 24 '18 at 09:09
8

Updated for ECMAScript 8 / await

The incorrect ECMAScript 8 demo code MongoDB inc provides also creates this warning.

MongoDB provides the following advice, which is incorrect

To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

Doing this will cause the following error:

TypeError: final argument to executeOperation must be a callback

Instead the option must be provided to new MongoClient:

See the code below:

const DATABASE_NAME = 'mydatabase',
    URL = `mongodb://localhost:27017/${DATABASE_NAME}`

module.exports = async function() {
    const client = new MongoClient(URL, {useNewUrlParser: true})
    var db = null
    try {
        // Note this breaks.
        // await client.connect({useNewUrlParser: true})
        await client.connect()
        db = client.db(DATABASE_NAME)
    } catch (err) {
        console.log(err.stack)
    }

    return db
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
7

The complete example for Express.js, API calling case and sending JSON content is the following:

...
app.get('/api/myApi', (req, res) => {
  MongoClient.connect('mongodb://user:password@domain.com:port/dbname',
    { useNewUrlParser: true }, (err, db) => {

      if (err) throw err
      const dbo = db.db('dbname')
      dbo.collection('myCollection')
        .find({}, { _id: 0 })
        .sort({ _id: -1 })
        .toArray(
          (errFind, result) => {
            if (errFind) throw errFind
            const resultJson = JSON.stringify(result)
            console.log('find:', resultJson)
            res.send(resultJson)
            db.close()
          },
        )
    })
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Roman
  • 19,236
  • 15
  • 93
  • 97
7

The following work for me for the mongoose version 5.9.16

const mongoose = require('mongoose');

mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);

mongoose.connect('mongodb://localhost:27017/dbName')
    .then(() => console.log('Connect to MongoDB..'))
    .catch(err => console.error('Could not connect to MongoDB..', err))
Guruprasad
  • 753
  • 6
  • 23
Lalit Tyagi
  • 264
  • 2
  • 10
4

Here's how I have it. The hint didn't show on my console until I updated npm a couple of days prior.

.connect has three parameters, the URI, options, and err.

mongoose.connect(
    keys.getDbConnectionString(),
    { useNewUrlParser: true },
    err => {
        if (err) 
            throw err;
        console.log(`Successfully connected to database.`);
    }
);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hashasaur
  • 41
  • 3
3

We were using:

mongoose.connect("mongodb://localhost/mean-course").then(
  (res) => {
   console.log("Connected to Database Successfully.")
  }
).catch(() => {
  console.log("Connection to database failed.");
});

→ This gives a URL parser error

The correct syntax is:

mongoose.connect("mongodb://localhost:27017/mean-course" , { useNewUrlParser: true }).then(
  (res) => {
   console.log("Connected to Database Successfully.")
  }
).catch(() => {
  console.log("Connection to database failed.");
});
Community
  • 1
  • 1
2
const mongoose = require('mongoose');

mongoose
  .connect(connection_string, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => {
    console.log("connected to db");
  });

try to use this

bhargav3vedi
  • 521
  • 1
  • 6
  • 11
1

I was using mlab.com as the MongoDB database. I separated the connection string to a different folder named config and inside file keys.js I kept the connection string which was:

module.exports = {
  mongoURI: "mongodb://username:password@ds147267.mlab.com:47267/projectname"
};

And the server code was

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

// Database configuration
const db = require("./config/keys").mongoURI;

// Connect to MongoDB

mongoose
  .connect(
    db,
    { useNewUrlParser: true } // Need this for API support
  )
  .then(() => console.log("MongoDB connected"))
  .catch(err => console.log(err));

app.get("/", (req, res) => res.send("hello!!"));

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

app.listen(port, () => console.log(`Server running on port ${port}`)); // Tilde, not inverted comma

You need to write { useNewUrlParser: true } after the connection string as I did above.

Simply put, you need to do:

mongoose.connect(connectionString,{ useNewUrlParser: true } 
// Or
MongoClient.connect(connectionString,{ useNewUrlParser: true } 
    
turivishal
  • 34,368
  • 7
  • 36
  • 59
zibon
  • 35
  • 4
1

These lines did the trick for all other deprecation warnings too:

const db = await mongoose.createConnection(url, { useNewUrlParser: true });
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
fedu
  • 138
  • 1
  • 8
1

I am using mongoose version 5.x for my project. After requiring the mongoose package, set the value globally as below.

const mongoose = require('mongoose');

// Set the global useNewUrlParser option to turn on useNewUrlParser for every connection by default.
mongoose.set('useNewUrlParser', true);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
STREET MONEY
  • 534
  • 4
  • 8
1

This works for me nicely:

mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology", true);
mongoose
  .connect(db) //Connection string defined in another file
  .then(() => console.log("Mongo Connected..."))
  .catch(() => console.log(err));
Chamon Roy
  • 731
  • 5
  • 8
0

If username or password has the @ character, then use it like this:

mongoose
    .connect(
        'DB_url',
        { user: '@dmin', pass: 'p@ssword', useNewUrlParser: true }
    )
    .then(() => console.log('Connected to MongoDB'))
    .catch(err => console.log('Could not connect to MongoDB', err));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Saahithyan Vigneswaran
  • 6,841
  • 3
  • 35
  • 45
0

(node:16596) 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) (node:16596) [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.

Usage:

async connect(connectionString: string): Promise<void> {
        this.client = await MongoClient.connect(connectionString, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
  })
        this.db = this.client.db()
}
Jamal Kaksouri
  • 1,684
  • 15
  • 22