I'm trying to connect to a MongoDB database with a username and password using Mongoose in Node.js. All the docs say that the connection string should look like

  mongodb://username:[email protected]:port/db

However, the password contains the '@' character in it. How can I make a connection string out of this that mongoose will understand? Can I escape the '@' in the password or is there another method of connecting I have to use?

Solution 1

Use this syntax:

// use %40 for @
mongoClient.connect("mongodb://username:p%[email protected]:port/dbname?authSource=admin", { 
        useNewUrlParser: true
    }, function(err, db) {


Solution 2

If your password has special characters:

const dbUrl = `mongodb://adminUsername:${encodeURIComponent('adminPassword')}@localhost:27017/mydb`;

Solution 3

Use the options parameter of the mongoose.connect call to specify the password instead of including it in the URL string:

                 {user: 'username', pass: '[email protected]'},

Solution 4

Try this one, my friends:

                     {user: 'viettd', pass: '[email protected]'});

test is my db name
admin is my the db for authenticating
viettd is my username
[email protected] is my password

Solution 5

I have also faced the same issue. I have solved by adding encoded password into connection string. And it works just well.

(1) Encode your password from
(2) Replace your password with encoded one.
(3) It should work well.

For example:
Actual Password: ABCDEX$KrrpvDzRTy`@drf.';3X
Encoded Password: ABCDEX%24KrrpvDzRTy%60%40drf.%27%3B3X

mongodb://user1:ABCDEX%24KprpvDzRTy%60%40drf.%27%[email protected]:1234,',

Solution 6

use pwd instead pass, that worked for me for version3.2

                 {user: 'username', pwd: '[email protected]'},

Solution 7

If you use Mongodb native Node.js driver, this is what works for me as of 3.1 driver version. Assume your url doesn't contain auth info.

MongoClient = require('mongodb').MongoClient;
let options = {
    useNewUrlParser: true,
    auth: {
        user: 'your_usr',
        password: 'your_pwd'
MongoClient.connect(url, options, callback);

Or if you wanna include auth info in your url, do this:

let url = "mongodb://username:" + encodeURIComponent("[email protected]") + "@localhost:27017/database"

Solution 8

None of the solutions mentioned above worked for me. I researched it further and found out that I had to include the useNewUrlParser parameter.

mongoose.connect(db, {
    useNewUrlParser : true
    err => {
    if (err){
        console.error('Error: ' + err)
        console.log('Connected to MongoDb')

From what I understand, you need a specific version of MongoDB in order to use this. For more details, check Avoid current URL string parser is deprecated warning by setting useNewUrlParser to true

It is to get rid of the warning but clearly the version also affect the required parameter.

I haven't tested all special characters but it definitely works with '@#$'.

Hope this helps.

Solution 9

sometimes you need to connect to the DB using other tools that accept string only as connection string. so just change the @ sign with %40

Solution 10

This solution requires an extra dependency, but it was what finally worked for me.

Add mongodb-uri to your project and the following lines to your code:

const mongoose = require('mongoose')
const mongodbUri = require('mongodb-uri')
let mongooseUri = mongodbUri.formatMongoose(config.mongo.uri)
mongoose.connect(mongooseUri, config.mongo.options)

I found this suggestion in mongoose's GitHub issue #6044.

Solution 11

Use this,

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true}).then(()=>console.log("DB connected"));

Solution 12

If the username or password includes the at sign @, colon :, slash /, or the percent sign % character, use percent encoding.

Mongo Docs:

Solution 13

I was attempting this in python and I had a similar error. This worked for me.

import pymongo

client = pymongo.MongoClient("mongodb://username:12%[email protected]:27017/sample_db") 
db = client.sample_db
# print the number of documents in a collection

12%40password represents your password and assumes it has a special character (e.g. @ - represented by %40) - username is your mongodb username , ip - your ip address and sample_db the database under mongodb that you wish to connect to.

Solution 14

This one worked for me

This one is a MongoDB 2020 Update If You're using a separate env file then just add your

    useNewUrlParser: true, 
    useUnifiedTopology: true 

Solution 15

Apparently I faced something similar, but I was not able to find any way around it other than avoiding special characters in password. I tried other special characters (^ % &) none of them works with the password in URL string. But the MongoDB doc says only

: / ? # [ ] @

these characters need to be percent-encoded.

I tried encoding most of them in my password combinations, but none of them are working.

Solution 16

Also, if your password contains a percentage, %, Because the percent ("%") character serves as the indicator for percent-encoded octets, it must be percent-encoded as "%25" for that octet to be used as data within a URI

for example, if your password is John%Doe, the new transformed password will be John%25Doe or If password is Paul%20Wait, New Password will be Paul%2520Wait

mongoClient.connect("mongodb://username:John%[email protected]:port/dbname", function(err, db) {
// password is John%Doe
    }`enter code here`