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
Related
I am using Youtube tutorial about API using MongoDB and mongoose. However,I am keep getting this error whenever I do POST something on Postman.
"MongooseError: Operation products.insertOne() buffering timed out after 10000ms"
const { MongoClient } = require('mongodb');
const uri = "mongodb+srv://dusdn1102:" + process.env.MONGO_PW + "#node-rest-shop.wvxmj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
client.close();
});
I am using visual studio code 1.57.1 and the version of MongoDB is 4.4.10.
Please can someone help me??
This will help you.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test')
.then(()=>console.log("DB Connected"))
.catch((err)=>console.log(err))
if you're using the mongoose model use this connection setting or as mentioned in mongoose website
You need to use mongoose to create a connection with the MongoDB. Add the following code to your app.js or server.js first.
const mongoose = require("mongoose");
const uri = "mongodb+srv://dusdn1102:" + process.env.MONGO_PW + "#node-rest-shop.wvxmj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", function () {
console.log("Connected successfully");
});
Use this to open a connection and then proceed with the insert operation.
I am trying to use multiple database connections in fastify with mongoose.
for single db code looks like
const mongoose = require('mongoose');
const fastifyPlugin = require('fastify-plugin')
mongoose.Promise = Promise; // Set mongoose to use ES6 Promises.
const reconnectTimeout = 5000; // ms.
const db = mongoose.connection;
async function dbConnector1(fastify, options) {
const conn1 = mongoose.connect("mongodb://localhost/db1", {
useNewUrlParser: true,
useUnifiedTopology: true,
retryWrites: false
})
.then(() => console.log( 'Connection to DB1 successful'))
.catch((err) => console.error(err));
};
module.exports = fastifyPlugin(dbConnector1,{
name: 'DB1'
})
I have put the above code in conn1.js
I have created a similar connection with different db in conn2.js and in index.js I am registering the db plugin as follows
await fastify.register(require('./src/db/conn1'))
await fastify.register(require('./src/db/conn2'))
I get the following error -
MongooseError: Can't call openUri() on an active connection with different connection strings. Make sure you aren't calling mongoose.connect() multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections
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.
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);
In local mongodb is running when i connect to mongodb atlas it is not connecting and there is no errors.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://NaveenS:naveen#frozenexpression-
jiptd.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, {useNewUrlParser: true,
useUnifiedTopology: true} );
client.connect(err => {
const collection = client.db("yelp_camp").collection("campgrounds");
client.close();
});
In uri your database name is test and you trying to connect 'yelp_camp' so write both same and try again.