Austin Johnson
Austin Johnson

Reputation: 747

Connecting a node api to a cosmosdb

I'm am trying to connect my react app with a node api to my cosmos db. I'm able to get the server running but when I send a post or get request I don't get a response. I've updated the firewall to allow my ip and I've read just about every article I can find on connecting to cosmos, but none of the resources have helped.

Here is the connection code

const mongoose = require('mongoose');
const env = require('./env/environment');
mongoose.set('useNewUrlParser', true);
mongoose.set('useUnifiedTopology', true);

mongoose.Promise = global.Promise;

const mongoUri = `mongodb://${env.dbName}:${env.key}@${env.dbName}.mongo.cosmos.azure.com:${env.cosmosPort}/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@${env.dbName}@`;

function connect() {
  return mongoose.connect(mongoUri, { auth: { user: env.dbName, password: env.key }});
}

module.exports = {
  connect,
  mongoose
};

and then the env file looks like this

const cosmosPort = 1234; // replace with your port
const dbName = 'your-cosmos-db-name-goes-here';
const key = 'your-key-goes-here';

module.exports = {
  cosmosPort,
  dbName,
  key
};

The env file has the actual information this is just an example.

Upvotes: 0

Views: 416

Answers (2)

Austin Johnson
Austin Johnson

Reputation: 747

I think your mongoUri need to be in this format mongodb://${env.dbName}:${env.key}@${env.dbName}.mongo.cosmos.azure.com:${env.cosmosPort}/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@${env.dbName}@

Took some digging for me, and the documentation isn't great.

Upvotes: 0

Jason Pan
Jason Pan

Reputation: 21883

Are you sure .env file can use const to define params? I'm not sure that. But I follow the offical document, I can connnect cosmosdb successfully.

enter image description here

It is recommended to refer to my screenshot, create a .env file, and replace your parameters to try.

var mongoose = require('mongoose');
var env = require('dotenv').config();
mongoose.connect("mongodb://"+process.env.COSMOSDB_HOST+":"+process.env.COSMOSDB_PORT+"/"+process.env.COSMOSDB_DBNAME+"?ssl=true&replicaSet=globaldb", {
  auth: {
    user: process.env.COSMODDB_USER,
    password: process.env.COSMOSDB_PASSWORD
  },
useNewUrlParser: true,
useUnifiedTopology: true,
retryWrites: false
})
.then(() => console.log('Connection to CosmosDB successful'))
.catch((err) => console.error(err));

Upvotes: 1

Related Questions