MongoDB password with “@” in it

前端 未结 16 1792
遇见更好的自我
遇见更好的自我 2020-11-27 14:03

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

<         


        
相关标签:
16条回答
  • 2020-11-27 14:20

    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("p@ssword") + "@localhost:27017/database"
    
    0 讨论(0)
  • 2020-11-27 14:21

    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 https://www.url-encode-decode.com
    (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%3B3X@dstest.com:1234,ds1234-test.com:19889/mongo-dev?replicaSet=rs-ds123546978&ssl=true',

    0 讨论(0)
  • 2020-11-27 14:22

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

    Mongo Docs: https://docs.mongodb.com/manual/reference/connection-string/

    0 讨论(0)
  • 2020-11-27 14:26

    Use this,

    mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true}).then(()=>console.log("DB connected"));
    
    0 讨论(0)
  • 2020-11-27 14:27

    If your password has special characters:

    const dbUrl = `mongodb://adminUsername:${encodeURIComponent('adminPassword')}@localhost:27017/mydb`;
    
    0 讨论(0)
  • 2020-11-27 14:29

    Try this one, my friends:

        mongoose.connect("mongodb://localhost:27017/test?authSource=admin",
                         {user: 'viettd', pass: 'abc@123'});
    

    test is my db name
    admin is my the db for authenticating
    viettd is my username
    abc@123 is my password

    0 讨论(0)
提交回复
热议问题