I have a node.js application that is deployed to azure using CosmosDB and the MongoDB API. My application uses mongoose which works seamlessly in 4.13.9.
My application
To connect to local cosmos db emulator use the following connection method (for mongoose > 5.0.0):
mongoose.connect(
`mongodb://localhost:10255/?ssl=true`,
{
auth: {
user: "localhost",
password: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
dbName: "admin"
}
}
);
Or you may also do the following:
const encodedPassword = encodeURIComponent("C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");
mongoose.connect(`mongodb://localhost:${encodedPassword}@localhost:10255/admin?ssl=true`);
Connection string has following format:
mongodb://username:password@host:port/[database]?ssl=true
and there seems to be some issue with default password character escaping. Thus we encoded it separately.
Add the new url parser as an option { useNewUrlParser: true }
Change you line 3 to:
mongoose.connect(configDB.url, { useMongoClient: true, useNewUrlParser: true } );
For the latest version (v5.0.1) of Mongoose, you'll need to use this syntax to connect to MongoDB like this:
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));
The password for the Azure Cosmos DB instance I got ended with ==
, hence the illegal characters message. These characters must be urlencoded.
An equals sign =
urlencoded is %3D
.
A properly encoded connection string for the password jitsu==
could look like mongodb://user:jitsu%3D%3D@localhost:27017/dbname?ssl=false
.
Also be aware that the connection strings you get from the Cosmos DB blade in the Azure Portal doesn't include the database name.