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
<
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"
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',
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/
Use this,
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true}).then(()=>console.log("DB connected"));
If your password has special characters:
const dbUrl = `mongodb://adminUsername:${encodeURIComponent('adminPassword')}@localhost:27017/mydb`;
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