Error connecting to Azure: invalid character in password with mongoose 5.0.1, but works in 4.13.9.

I have a node.js application that is deployed on azure using CosmosDB and the MongoDB API. My application uses mongoose, which works easily in 4.13.9.

My application that works is connected as follows:

var configDB = require('./config/database'); var mongoose = require('mongoose'); mongoose.connect(configDB.url, { useMongoClient: true } ); mongoose.Promise = global.Promise; var db = mongoose.connection; db.on('error', console.error.bind(console, 'MongoDB connection error:')); 

The config / database file is defined as follows (username, password, DB changed to protect the innocent):

 module.exports = { 'url': 'mongodb://azureusername: azurepassword@myazuredb.documents.azure.com :10255/?ssl=true' } 

Now the problem occurs when I install mongoose 5.0.1. I remove the useMongoClient parameter from the connection and get rid of the promise, so my connection code is now:

 mongoose.connect(configDB.url); var db = mongoose.connection; db.on('error', console.error.bind(console, 'MongoDB connection error:')); 

When this is done, I get the following in the console:

(node: 21392) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Password contains illegal unescaped character

I can even comment on the connection code where it is only mongoose.connect, and this is what gives the error. What am I doing wrong? Is there a 5.0.1 change that I need to consider? As a side note, which may or may not be related, I saw a few notes about what now gives a callback instead of using promises, so if someone has an example of how they do this in a Node / Express application, which would be great, but it doesn't look like isee when I get an error message related to an illegal character. NOTE. The configuration file is exactly the same if it works with versions 4.13.9 or 5.0.1, so I know that the password is valid and that is not a problem.

+5
source share
2 answers

For the latest version (v5.0.1) of Mongoose, you will need to use this syntax to connect to MongoDB as follows:

 const mongoose = require('mongoose'); mongoose.connect('mongodb://<cosmosdb-username>.documents.azure.com:10255/<databasename>?ssl=true', { auth: { user: '<cosmosdb-username>', password: '<cosmosdb-password>' } }) .then(() => console.log('connection successful')) .catch((err) => console.error(err)); 
+8
source

The CosmoDB password I received through Azure ended == , hence the message about illegal characters. However, they can be urlencoded, as it should be, in a valid URI.

Equal Sign = urlencoded - %3D .

The connection string for the jitsu== password might look something like mongodb://user:jitsu%3D% 3D@localhost :27017/dbname?ssl=false .

+1
source

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


All Articles