Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

current URL string parser is deprecated in mongo db and nodejs

I am using mongodb and nodejs 8 to connect to database but I get this error :

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

my codes :

mongoose.connect(db,(err) => {
            if (err)
                console.error(err);
            else
                console.log("Connected to the mongodb");
        });
like image 437
Artin Zareie Avatar asked Sep 17 '18 20:09

Artin Zareie


People also ask

How does MongoDB connect to node js database?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });

What is useNewUrlParser MongoDB?

useNewUrlParser : 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.

What is useUnifiedTopology true?

useUnifiedTopology: False by default. Set to true to opt in to using the MongoDB driver's new connection management engine. You should set this option to true , except for the unlikely case that it prevents you from maintaining a stable connection.


2 Answers

Change your code to:

mongoose.connect(db, {useNewUrlParser: true}, (err) => {
    if (err)
        console.error(err);
    else
        console.log("Connected to the mongodb"); 
});

You are getting this error because you are using a newer version (>=4.0.0) of MongoClient

like image 85
D_________ Avatar answered Sep 30 '22 20:09

D_________


If it fails too, you need to add {useUnifiedTopology: true } to the code. It looks like:

mongoose.connect(db, {useNewUrlParser: true, useUnifiedTopology: true }, (err) => {
  if (err)
     console.error(err);
  else
     console.log("Connected to the mongodb"); 
});
like image 34
victor alvarez Avatar answered Sep 30 '22 21:09

victor alvarez