Cannot connect to MongoDB in Azure

I have MongoDB on Azure and am trying to connect to it using the npm mongodb module:

var mongoClient = require("mongodb").MongoClient; mongoClient.connect("mongodb://myuser: mypassword@myhost.documents.azure.com :10355/?ssl=true", function (err, db) { db.close(); }); 

Password

My password has the following characteristics:

  • Contains letters, lowercase, uppercase
  • Without spaces
  • Contains numbers
  • Contains special characters such as = , @ , $ , etc.

Error

When executing the code above, I get the following:

 Error: Password contains an illegal unescaped character at parseConnectionString (C:\Users\myuser\Documents\myproj\node_modules\mongodb\lib\url_parser.js:280:13) 

However, the documentation says a lot about how to solve this problem. I assume this is a coding problem. How to fix it?

+5
source share
2 answers

Characters like @ are limited because they ruined the structure of the URL. The reason for this is because MongoDB interprets this as an @ delimiter. Instead of this:

 var mongoClient = require("mongodb").MongoClient; mongoClient.connect("mongodb://myuser: myp@ssword @myhost.documents.azure.com:10355/?ssl=true", function (err, db) { db.close(); }); 

use this

 mongoClient.connect("mongodb://myuser:myp% 40ssword@myhost.documents.azure.com :10355/?ssl=true", { uri_decode_auth: true }, function (err, db) { db.close(); }); 

To encode a password, use encodeURIComponent(password)

You can also use this syntax.

 mongoClient.connect("mongodb://myhost.documents.azure.com:10355/?ssl=true", {user: 'username', pass: ' p@ssword '}, function (err, db) { db.close(); }); 

In later versions use

 auth: { user: 'username', password: ' p@ssword ', } 

as below

 mongoClient.connect("mongodb://myhost.documents.azure.com:10355/?ssl=true", { auth: { user: 'username', password: ' p@ssword ', }}, function (err, db) { db.close(); }); 
+7
source

The accepted answer does not work for me on mongodb> 3.0.x

This code works for me:

 const mongoClient = require("mongodb").MongoClient; let database = null; new mongoClient('mongodb://myhost.documents.azure.com:10355/?ssl=true', { auth: { user: 'username', password: ' p@ssword ', } }).connect( (err, db) => { if (err) return console.error(err); console.log('Database connected'); database = db.db('foo'); }); 
+2
source

Source: https://habr.com/ru/post/1274389/


All Articles