MongoDB password with “@” in it

2020-01-24 20:17发布

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:password@host: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?

12条回答
淡お忘
2楼-- · 2020-01-24 20:48

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

mongoose.connect('mongodb://localhost/test',
                 {user: 'username', pwd: 'p@ssword'},
                 callback);
查看更多
疯言疯语
3楼-- · 2020-01-24 20:53

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)
    }
    else{
        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.

查看更多
\"骚年 ilove
4楼-- · 2020-01-24 20:54
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%25Doe@host:port/dbname", function(err, db) {
// password is John%Doe
    }`enter code here`
);
查看更多
倾城 Initia
5楼-- · 2020-01-24 20:56

Use this syntax:

mongoClient.connect("mongodb://username:p%40ssword@host:port/dbname?authSource=admin", { 
        useNewUrlParser: true
    }, function(err, db) {

    }
);
查看更多
Root(大扎)
6楼-- · 2020-01-24 20:56

If your password has special characters:

const dbUrl = `mongodb://adminUsername:${encodeURIComponent('adminPassword')}@localhost:27017/mydb`;
查看更多
聊天终结者
7楼-- · 2020-01-24 20:56

Use the options 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: 'p@ssword'},
                 callback);
查看更多
登录 后发表回答