node.jsmongodbmean-stack

Can not connect to the databaseMongoParseError: Unescaped at-sign in authority section


I am trying to connect to mongodb server in my nodeJS project. I have a db config file as DB.js

module.exports = {
    DB: 'mongodb+srv://user%40gmail.com:%24ugar@cluster-jfgsm.mongodb.net/test?retryWrites=true'
 };

username contains @ (%40) mark as it is an email id and the password contains $(%24) characters.

And i have connected that in my server.js file as

    mongoose = require('mongoose'),
    config = require('./config/DB');

    const app = express();

    mongoose.Promise = global.Promise;
    mongoose.connect(config.DB,  { useNewUrlParser: true } ).then(
      () => {console.log('Database is connected') },
      err => { console.log('Can not connect to the database'+ err)}
    );

and I have added the custom serve option in my package.json file to run the nodemon.

"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "serve": "nodemon server.js"
  },

But when i tried to run the project using the command npm run serve, i am getting an error message in the console

Can not connect to the databaseMongoParseError: Unescaped at-sign in authority section

I have searched many questions in the stack-overflow also but nothing worked for me.

Any help is appreciated. Thank You


Solution

  • It's okay to encode the password like so:

    const DB_USER = 'user';
    const PASSWORD = encodeURIComponent('hello@123'); 
    const DB_URL = `mongodb://${DB_USER}:${PASSWORD}@ds331735.mlab.com:31772/any_db`;
    

    If there's an @ in your password, you should change it to %40.