Connecting a node api to a cosmosdb - node.js

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.

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.
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));

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.

Related

MongoDB manage access from node js server

I have a node js server with a MongoDB. Can I do a 2 simultaneous connections to DB with different users?
Here is my connect code:
const mongoose = require("mongoose");
const { DB } = require("../constants");
const connectDB = async () => {
await mongoose.connect(DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
};
export const connect = connectDB;
I want make 2 connections, for example:
DB1 = mongodb+srv://USER:password#.mongodb.net
DB2 = mongodb+srv://USER1:password#.mongodb.net
Is it possible to do this in node js?
I can imagine yes since there are two instances, I think the most obvious response is you will never know until you try :D

Unable to connect to mongodb databse using node.js

I am unable to connect to mongodb from node.js using mongoose as database driver. Also I am getting the following error.
Error:
Error in DB connection:{"ok":0,"code":18,"codeName":"AuthenticationFailed","name":"MongoError"}
I am explaining my code below.
const mongoose = require('mongoose');
const dbUser = process.env.USERNAME || 'admin';
const dbPass = process.env.PASSWORD || 'admin';
const dbServer = 'edqart-mongodb';
const dbPort = process.env.MONGO_PORT || '27017';
let dbName = 'edqart-db';
const url = `mongodb://${dbUser}:${dbPass}#${dbServer}:${dbPort}/${dbName}`;
console.log('url', url);
const options = {
useNewUrlParser: true,
useCreateIndex: true,
connectTimeoutMS: 5000000,
poolSize: 10000,
useUnifiedTopology: true
};
/*
1- Connect to mongo server
*/
mongoose.connect(url, options, (err) => {
if(!err) {
console.log('Mongodb connection with mongoose successed');
} else {
console.log('Error in DB connection:' + JSON.stringify(err, undefined, true));
}
})
Here the database edqart-db is not actually present inside that particular mongo server. I need once one record will insert the db will created dynamically. If I have let dbName = 'admin'; then my node is connected to mongodb but for other db which is not created from beginning its showing error. I need once one record is going to insert then the db edqart-db will created. Here I just need the similar method like client.db(dbName) of require('mongodb').MongoClient for mongoose also.
I don't think its possible to authenticate on non existing db.
Here is what you should do if you want to enable auth on edqart-db.
Create a database edqart-db.
Create a user on that edqart-db. lets say username=edqartReadUser and password=edqartReasPassword.
Then your existing code should work below url.
const dbUser = process.env.USERNAME || 'edqartReadUser';
const dbPass = process.env.PASSWORD || 'edqartReasPassword';
const dbServer = 'edqart-mongodb';
const dbPort = process.env.MONGO_PORT || '27017';
let dbName = 'edqart-db';
const url = `mongodb://${dbUser}:${dbPass}#${dbServer}:${dbPort}/${dbName}`;

What should I do to connect mongoose 5.8 with mongodb?

I'm using mongoose. 5.8.2 and following a tutorial where the person is running mongoose on v3.5. I know there has been changes like useNewUrlParser has been deprecated and instead we use useUnifiedTopology but the problem is that whenever I use useUnifiedTopology then I get the error that it has been deprecated. Please have a look below and let me know what am I doing wrong
const mongoose = require('mongoose')
mongoose.createConnection('mongodb://127.0.0.1:27017/task-manager-api', {
useUnifiedToplogy: true,
useCreateIndex: true
});
const User = mongoose.model('User', {
name: {
type: String
},
age: {
type: Number
}
})
const me = new User({
name: 'Lallan',
age: '27'
})
me.save().then(() => {
console.log('Done')
}).catch((error) => {
console.log('error', error)
})
and the following is the error and I'm not able to connect mongoose with mongodb
the options [useUnifiedToplogy] is not supported
(node:6573) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:6573) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
What should I do to connect mongoose with mongodb?
The most default connection will be to just { useNewUrlParser: true }. You can use createConnection()(for multiple pools) as well as connect()(single pool).
From MDN a basic example will be:
//Import the mongoose module
var mongoose = require('mongoose');
//Set up default mongoose connection
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB, { useNewUrlParser: true });
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
Also,
If you need to create additional connections you can use
mongoose.createConnection(). This takes the same form of database URI
(with host, database, port, options etc.) as connect() and returns a
Connection object.
like,
const db = mongoose.createConnection('mongodb://user:pass#localhost:port/database', opts);
Maybe try giving it this way,
const mongoose = require('mongoose');
let db_uri = "'mongodb://localhost:27017/mydb"
mongoose.connect(db_uri, {
useNewUrlParser: true,
useUnifiedTopology : true
});
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);

Unable to connect to MongoDB cloud by following code. I need to know whats wrong with this code?

I am unable to connect to cloud mongodb with the following code. Can anyone please tell me whats wrong with this code?
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
//body parser middleware
app.use(bodyParser.json());
//db config
const db = require('./config/keys').mongoURI;
//Connect to mongo
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server started on port ${port}'));
There are multiple steps you should follow to be able to connect Mongo DB so first make sure that you created an account plus connecting to a cluster, while creating it you'll be provided with enough info to create a cluster take your time and read.
after doing that the code is very simple:
const mongoose = require("mongoose");
mongoose.connect(
"mongodb+srv://[ACCOUNT NAME]:[PASSWORD]#cluster0-sxlgp.gcp.mongodb.net/test?retryWrites=true&w=majority", { useNewUrlParser: true }
);
replace ACCOUNTNAME and PASSWORD with info you provided when you created your MongoDB account
This can be found in their documentation try taking your time reading the documentation.
I believe your code looks good the error you are getting TransientTransactionError is temporary please use events to handle your connection result
mongoose
.connect(db, { useNewUrlParser: true })
mongooose.connection.once('open', () => {
console.log('db connection success');
});
mongooose.connection.on('err', (err) => {
console.log('db connection failed');
});

Use single database connection in entire application?

I am creating a application that will communicate over Udp protocol in node js. Also i am using sql server as a database so in order to connect this database i am using mssql npm liabrary. Basically what i am doing i have one separate module for dbcon as shown below
const sql = require('mssql')
const config = {
user: 'sa',
password: '123',
server: '192.168.1.164', // You can use 'localhost\\instance' to connect to named instance
database: 'SBM-EMCURE',
options: {
encrypt: false // Use this if you're on Windows Azure
}
}
sql.connect(config, err => {
})
sql.on('error', err => {
console.log('error on sql.on()');
})
module.exports.sql = sql;
And i am using this exported sql object to run my queries outside dbcon module but it gives me different behavior sometimes like query executes before databse connection, is there is any way to use single database connection for entire application?. Using single database connection is useful or it will slow down my process
Thanks in advance
You could:
Pass the instance into each router and use it there when you set them up
Set the instance as a property of your app object and access it from req.app.sql or res.app.sql within your middleware functions
Set the instance as a property of the global object and access it from anywhere (typically not a best practice though)
Also, in your example code, you're initiating the connection by calling sql.connect(), but you don't give it a callback for when it's finished connecting. This is causing it to be immediately exported and probably queried before the connection is actually established. Do this:
const util = require('util');
const sql = require('mssql');
const config = {
user: 'sa',
password: '123',
server: '192.168.1.164',
database: 'SBM-EMCURE',
options: {
encrypt: false
}
};
module.exports = util.promisify(sql.connect)(config);
Then you can retrieve the instance with:
const sql = await require('./database.js');
first you should create file database.js:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'event'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
Then you can use this connection in server.js or any other file.
var express = require('express');
var app = express();
var dbcon = require('./database');
app.get('/getEvent',function(req,res){
dbcon.query('SELECT * FROM eventinfo',function(err, result) {
if (err) throw err;
});
});
app.listen(3000);

Resources