NodeJS [SOLVED]: Cannot connect to MongoDB in Azure

NodeJS [SOLVED]: Cannot connect to MongoDB in Azure

Home Forums Scripting NodeJS Tutorials NodeJS [SOLVED]: Cannot connect to MongoDB in Azure

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #245865

    Cloudy Point
    Keymaster

    QuestionQuestion

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

    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
    • No white space
    • Contains numbers
    • Contains special characters like =, @, $ and so on

    Error

    I get the following when executing the code above:

    Error: Password contains an illegal unescaped character
        at parseConnectionString (C:UsersmyuserDocumentsmyprojnode_modulesmongodbliburl_parser.js:280:13)
    

    However the documentation does not tell much about how to solve this issue. I guess it is an encoding problem. How to fix this?

    #245866

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    Characters like @ are restricted as they mess up the structure of the URL.
    The reason for this is because MongoDB interprets it as the @ separator. 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 the 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();
    });
    

    Source: https://stackoverflow.com/questions/48029723/cannot-connect-to-mongodb-in-azure
    Author: Solver
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.