typeorm/mongo-typescript-example

DeprecationWarning: current URL string parser is deprecated

foli opened this issue Β· 50 comments

foli commented

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

is there any way to pass the new option, the data does get saved though

DeprecationWaringin: Current UEL string parser is deprecated and will be removed in future version

how to solve this error?

use this
mongoose.connect('mongodb://user:password@sample.com:port/dbname', { useNewUrlParser: true })

to avoid this problem use this
MongoClient.connect(url, {useNewUrlParser: true } )

when using MongoClient.connect(url, {useNewUrlParser: true } ) Im getting this new warning

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()

I have the same error. Any solution?

Here is what I did
db.mongoConnect = () => {
mongoose.Promise = global.Promise
mongoose.connect(config.mongo.mongodb_url, {useNewUrlParser: true})
.then(() => {
console.log('mongoDB is connected...')
})
.catch((err) => {
throw err
})
}

HI @grety22 , @Brayan1013 and @skyerh i have tried all your options but keep chasing my tail :) so any further ideas will be appreciated.

In its original form, this is what i had:
const express = require('express');
const mongoose = require('mongoose');
...
...
...

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

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

And it has worked fantastic for past three weeks until this morning. Then one by one i tried all your options but keep still getting the error below in different forms:

"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."

Then, I tried to adapt it to:

const express = require('express');
const mongoose = require('mongoose');
const { MongoClient } = require('mongodb');
const mongoURI = 'mongodb://localhost:27017';
...
...
...

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

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

No luck. Instead, i now started getting errors:

"Server on port 5000
{ MongoNetworkError: failed to connect to server [ds227858.mlab.com:27858] on first connect [MongoNetworkError: connect ETIMEDOUT 52.49.63.15:27858]" etc etc

I also tried adapting what @grety22 and @skyerh has and still no luck.

@Hixsav I think your error is different to the topic.
It looks like a network connection error ?

Server on port 5000
{ MongoNetworkError: failed to connect to server [ds227858.mlab.com:27858] on first connect [MongoNetworkError: connect ETIMEDOUT 52.49.63.15:27858]" etc etc

Yes, but only after i try any of the solutions outlined here or elsewhere. Otherwise it remains as a deprecation warning. Which tells me the basic connection fundamentals seem ok, so long as the deprecation issue is solved. And when i try solve it, i get a connection error.

I think the connection error may have to do with with my keys.js file. But i am a newbie, have managed to scale this mountain until this morning. Its looking too high to scale beyond this..

Tried to use {useNewUrlParser: true} to get rid of the deprecation warning, but it resulted in all the backend calls involving DB access stalling (spinner, nothing is returned). Reverting to useNewUrlParser: false resolved the issue for now.

@jarecsni, can you perhaps explain further please, did u try using the original example above? Or are u referring to one u are also having problems with?

@jarecsni i think i understand you now! I reverted to my original code, and it worked! Only when i pay attention to the deprecation warning does my code break. So, i resolved to do nothing for now. Talk about playing ostrich :)

This works for me in the moment @Hixsav =)
mongoose.connect('url', { useNewUrlParser: true }, (err, res) => {
if (err) throw err;

console.log('Database online');

});

Thanks @Brayan1013 i will give it a try! :)

I get this warning
MongoError: port must be specified

after i added the code...
mongoose.connect('mongodb://user:password@sample.com:port/dbname', { useNewUrlParser: true })

const dbpath = "mongodb://localhost:27017/batch2";

const mongo = mongoose.connect(dbpath, {useNewUrlParser: true });
mongo.then(() => {
console.log('connected');
}).catch((err) => {
console.log('err', err);
});

This works for me, without any error or warning.

i had this issude. in server file for example app.js you should add this code

var mongoose = require('mongoose');
mongoose.connect('your url', { useNewUrlParser: true });
mongoose.set('useCreateIndex', true);

Solution is :

const mongoose = require('mongoose');

mongoose.set('useNewUrlParser', true)
mongoose.set('useFindAndModify', true)
mongoose.set('useCreateIndex', true)

conn = mongoose.createConnection(dbUrl)


OR as module: (FOLDER CONFIG/MONGOOSE.JS)

const mongoose = require('mongoose')
const { mongo, env } = require('./vars')

mongoose.Promise = Promise

mongoose.connection.on('error', (err) => {
console.error(MongoDB connection error: ${err})
process.exit(-1)
})

if (env === 'development') {
mongoose.set('debug', true)
}

exports.connect = () => {
mongoose.connect(mongo.dbUrl, {
keepAlive: 1,
reconnectTries: 30,
useFindAndModify: true,
useCreateIndex: true,
useNewUrlParser: true,
user: process.env.MONGO_USER,
pass: process.env.MONGO_PASSWORD,
auth: {
authdb: process.env.MONGO_DB
}
}).then(() => { return mongoose.connection },
err => { console.log(err) }
)
}

AND USE IN SERVER/INDEX:

const mongoose = require('./config/mongoose')
mongoose.connect()

HERE MORE INFOS
https://mongoosejs.com/docs/deprecations.html

Thanks a lot πŸ‘

I made a slight edit to your solution from above as in:

mongoose.set('useFindAndModify', true);
mongoose.set('useCreateIndex', true);
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log('MongoDB Connected'))
.catch((err) => console.log(err));

And this helped my resolve my week-long issues! :-)

Here is what I did
db.mongoConnect = () => {
mongoose.Promise = global.Promise
mongoose.connect(config.mongo.mongodb_url, {useNewUrlParser: true})
.then(() => {
console.log('mongoDB is connected...')
})
.catch((err) => {
throw err
})
}

what is initial db in that?
What should be there inside mongoConnect = () function parentheses?

Here is how I did it, note that if your're needs are GridFS or GridFS Storage you need additional params.
// AS A MODULE "server/mongoMongoose.js"
// USE CONNECTION ON PROJECT AS: "mongoConnect"

const mongoose = require('mongoose');

const mongoConnect = () => {
mongoose
.connect(
database,
{
useNewUrlParser: true,
useFindAndModify: true,
useCreateIndex: true,
keepAlive: 1,
reconnectTries: 30 // keep an eye open for performance and security
}
)
.then(() => console.log('Connected To Mongo!!'))
.catch(err => console.log(err));
};

module.exports = mongoConnect;

Hi guys, I simply added the {useNewUrlParser:true} argument and it passed perfectly with no error

mongoose.connect( 'URL string*' ,{useNewUrlParser:true});

@dinho-afsn This worked for me. Hats off to you!

this works for me.

// 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));

@olufemi424 Can you please tell me your MongoDB URI so I can compare it with mine?

hii @HixOba , can you please tell me what was the code that worked for you finally in both server.js and keys.js?

this is my URI linked in my keys.js
module.exports = {
mongoURI: "mongodb://:@ds147354.mlab.com:47354/friendconnect"
};

@olufemi424 Thanks! But for some reason it was not working for me (obviously after putting the right username and password). But my connection to the databse worked when I switched to MongoDB Atlas :)

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.
θΏ™δΈͺζ˜―ζ€ŽδΉˆε―Όθ‡΄ηš„?

let options = {useNewUrlParser: true};
let uri = 'mongodb://localhost/yourdbname';

mongoose.connect(uri, options).then(
() => {
    console.log('Connected to the database!')
},
    err => { console.log('Error! Could not connect') }
);

mongoose.connect('urlToDataBase', { useNewUrlParser: true })
This works for me.

Here the doc explained the reason:
https://mongoosejs.com/docs/connections.html
https://mongoosejs.com/docs/deprecations.html
Unfortunately, while i use createConnection function like this:mongoose.createConnection('mongodb://127.0.0.1:27017/test', { useNewUrlParser: true });,the warning still there.I believe it's mongoose's unfixed bug.

The test is under mongoose@5.4.17 on mac.

I tried all the alternatives above and realized that forgot to do the required steps to connect to MongoDB, which is installing and running mongo:
If you haven't tapped yet (using Homebrew):
brew tap mongodb/brew
then (assuming you don't want the enterprise version):
brew install mongodb-community@4.0
Run MongoDB:
mongod --config /usr/local/etc/mongod.conf

And at last start your app again.

Does this issue have anything to do with TypeORM? Seems to be full of questions about mongoose?

phifa commented

This worked for me:
mongoose.createConnection('mongodb://127.0.0.1:27017/test', { useNewUrlParser: true });

tbanj commented

mongoose.connect("mongodb://127.0.0.1:27017/vidly", { useNewUrlParser: true, useCreateIndex: true });

above code work for me , what was missing in my code initially is { useNewUrlParser: true, useCreateIndex: true } the ip & port number was different because i was making use of docker environment

How would we do this if we are not using mongoose take the typescript mongo repo as an example. This is similar to how my project is setup.

So I do not have mongoose.connect() or MongoClient.connect(). I am using the following and ormconfig.json

// Connects to the Database
const connection: Connection = await createConnection();
{
    "type": "mongodb",
    "url": "mongodb+srv://x:y@cluster?retryWrites=true&w=majority",
}

Edit, connect takes in ConnectionOptions, I just didn't read the error properly. It was complaining about wanting the type too. Then I notice well I can just add the property to ormconfig.json.

{
    "type": "mongodb",
    "useNewUrlParser": true,
    "url": "mongodb+srv://x:y@cluster?retryWrites=true&w=majority",
}

I wasted hours on trying to connect to mongodb

Hope this will help someone with "no users authenticated" and "failed to connect to server [localhost:27017] on first connect" errors

  1. Create a user for your database :
use DBNAME
db.createUser(
  {
    user: "DBUSER",
    pwd: "DBPASS",
    roles: [ { role: "readWrite", db: "DBNAME" },
  }
)
  1. Use 127.0.0.1 instead of localhost
const options: ConnectionOptions = {
    type: "mongodb",
    host: "127.0.0.1",
    database: "DBNAME",
    logging: ["query", "error"],
    username: "DBUSER",
    password: "DBPASS",
    synchronize: true,
    useNewUrlParser: true,
    entities: [User]
}
  1. Check firewall for remote host
  2. And finally connect to mongo..
await createConnection(options);

Use to avoid deprecated method
mongoose.connect('mongodb://localhost:27017/dbname', { useNewUrlParser: true, useUnifiedTopology: true } )

This works like sharm :

var mongoose = require('mongoose');

mongoose.connect(config.db_config.uri, { useUnifiedTopology: true ,useNewUrlParser: true })
    .then(() => {
        console.log('mongo connection created');
        resolve(db);
    })
    .catch(err => {
        console.log('error creating db connection: ' + err);
        reject(db);
    });
});

Good Luck !

i think you have to try ip whitelist default 0.0.0.0/0

Several issues can be happening:

  • Ip not whitelisted
  • Password needs to be encoded if it has special chars
  • Check the URL (if using atlas)
  • Then follow the errors until you get it to work

i got this error
(node:6404) 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.
(node:6404) 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 { useUni

i got this error
(node:6404) 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.
(node:6404) 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 { useUni

I raised this issue on stack overflow
on https://stackoverflow.com/questions/61711422/two-node63440-deprecation-warnings-at-the-same-time-current-url-string-parse

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

is there any way to pass the new option, the data does get saved though

const mongo = mongoose.connect(URI, {useNewUrlParser: true , useUnifiedTopology: true});
mongo.then(() => {
console.log('connected');
}).catch((err) => {
console.log('err', err);
});

just add these all
//////////////////////////////////
1.useNewUrlParser: true
2. useFindAndModify: true,
3. useCreateIndex: true,
4.useUnifiedTopology: true
//////////////////////////////////////////
example:
mongoose
.connect(url, {
useNewUrlParser: true,
useFindAndModify: true,
useCreateIndex: true,
useUnifiedTopology: true,
})
.then(() => console.log("DB Connected"))
.catch((err) => console.error(err));
you will never see any warning :-)

Use to avoid deprecated method
mongoose.connect('mongodb://localhost/db', { useNewUrlParser: true, useUnifiedTopology: true } )

This works for me (2021, January), getting warnings such:

(node:13552) 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.
(Use node --trace-deprecation ... to show where the warning was created)

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

is there any way to pass the new option, the data does get saved though

use this : mongoose.connect('mongodb://localhost/playground',{useUnifiedTopology : true,useNewUrlParser : true})
It worked for me .. :)