Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

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" 
like image 738
Lion Avatar asked May 21 '18 11:05

Lion


People also ask

What does useNewUrlParser true do?

The underlying MongoDB driver has deprecated their current connection string parser. Because this is a major change, they added the useNewUrlParser flag to allow users to fall back to the old parser if they find a bug in the new parser. You should set useNewUrlParser: true unless that prevents you from connecting.

How do you use useUnifiedTopology true?

How to use it. The unified topology is available now behind the useUnifiedTopology feature flag. You can opt in to using it by passing the option to your MongoClient constructor: const client = MongoClient('mongodb://localhost:27017', { useUnifiedTopology: true });

What is useCreateIndex?

the useCreateIndex option ensures that you are using the new function calls. Reference: https://mongoosejs.com/docs/connections.html#options https://mongoosejs.com/docs/deprecations.html. Follow this answer to receive notifications.


1 Answers

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.

like image 73
Abhishek Sinha Avatar answered Oct 18 '22 15:10

Abhishek Sinha