MongoDB password with “@” in it

前端 未结 16 1951
遇见更好的自我
遇见更好的自我 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"
    

提交回复
热议问题