Mongo DB Connection - Password contains unescaped characters

Viewed 2101

I am trying to connect to MongoDB but I am getting the "Password contains unescaped characters" error. I have included the useNewUrlParser:true option but I still get the error See my code below:

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");

dotenv.config();

connectDB().catch(err => console.log(err)); 

async function connectDB() {
await mongoose.connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
})
    .then(() => console.log("DB Connection Success"))
    .catch((err) => console.log(err));
}

app.listen(8800, () => {
console.log("Backend Server is running");
});
3 Answers

Same problem here... solved with encodeURIComponent on the part of the string that had the password

const uri = "mongodb+srv://username:" + encodeURIComponent("pass#") + "@cluster.yijnb.mongodb.net/db?retryWrites=true&w=majority";

Maybe provide username and password as option:

const options = {
  user: <username>,
  pass: <password>,
  authSource: "admin",
  useNewUrlParser: true
};
mongoose.connect(process.env.MONGO_URL, options);

I solved it by changing the password as I tried using several fixes to help me connect with the initial password that contained ".".

Related