MongoDB password with "@" in it

iZ. Source

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?

mongodbnode.jsmongoose

Answers

answered 5 years ago JohnnyHK #1

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

mongoose.connect('mongodb://localhost/test',
                 {user: 'username', pass: '[email protected]'},
                 callback);

Any of the parameters not used by mongoose.connect directly are passed through to the underlying native connection.open call which supports this.

answered 4 years ago Andrey Hohutkin #2

Use this syntax, don't forget the uri_decode_auth option.

mongoClient.connect("mongodb://username:p%[email protected]:port/dbname", { 
    uri_decode_auth: true 
    }, function(err, db) {

    }
);

answered 1 year ago Viet Tran #3

Try this one, my friends:

    mongoose.connect("mongodb://localhost:27017/test?authSource=admin",
                     {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

answered 1 year ago AKASH #4

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

mongoose.connect('mongodb://localhost/test',
                 {user: 'username', pwd: '[email protected]'},
                 callback);

answered 1 year ago dang #5

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

answered 1 month ago vanduc1102 #6

If your password has special characters:

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

answered 4 weeks ago Oduwole Oluwasegun #7

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

comments powered by Disqus