This is the code I use to connect to my database:
private connectDatabase(databaseUri: string): Promise<Mongoose.Connection> {
return Mongoose.connect(databaseUri).then(() => {
debug('Connected to MongoDB at %O', databaseUri);
return Mongoose.connection;
});
}
Today I updated Mongoose to version 4.11.0 and I got this warning when running my tests:
(node:4138) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using `connect()`
or `createConnection()`
I can't find any information on how to "set useMongoClient".
Do you guys know how to?
This is how you use useMongoClient:
mongoose.connect('mongodb://localhost/advisorDemoTestDB', { useMongoClient: true })
Add { useMongoClient: true } as another argument to connect or createConnection method, its depends on version of mongoose you are using.
// Using `mongoose.connect`...
var promise = mongoose.connect('mongodb://localhost/myapp', {
useMongoClient: true,
/* other options */
});
// Or `createConnection`
var promise = mongoose.createConnection('mongodb://localhost/myapp', {
useMongoClient: true,
/* other options */
});
mongoose.connection.openUri('mongodb://127.0.0.1/camp_v12')
has anyone tried this? my deprecated warning disappeared when i use this, it was from the documentation
http://mongoosejs.com/docs/connections.html
The easiest fix for this would be to open your terminal, change your directory to your root project (folder where package.json is)
Run:
npm remove mongoose
then:
npm install mongoose#4.10.8 --save
problem solved.
Upgrading is not always the best option.
http://mongoosejs.com/docs/connections.html
Without Typescript you can pretty much ignore the issue and use Mongoose.connect(databaseUri, { useMongoClient: true }).
If you really want to avoid having the warning avoid the version 4.11.0.
I updated to version 4.11.1 and since #types/mongoose#4.7.18 are not yet updated and they do not mention the field useMongoClient in the ConnectionOptions, this is how i imported the module:
const Mongoose = require('mongoose');
And then used this function:
private connectDatabase(databaseUri: string): Promise<any> {
return Mongoose.connect(databaseUri, { useMongoClient: true })
.then(() => {
console.log('Connected to MongoDB at ', databaseUri);
return Mongoose.connection;
})
.catch(err => debug(`Database connection error: ${err.message}`));
}
As many answers say, adding { useMongoClient: true } in options argument to connect or createConnection method will solve the problem.
For e.g.
// With mongoose.connect method
mongoose.connect('mongodb://localhost/app', { useMongoClient: true });
// With createConnection method
mongoose.createConnection('mongodb://localhost/app', { useMongoClient: true });
But what is MongoClient in the first place?
From MongoDB Node.js Driver version 1.2, a new connection class MongoClient was introduced that has the same name across all the official drivers.
The new connection class MongoClient acknowledges all writes to MongoDB, in contrast to the existing DB connection class which has acknowledgements turned off.
So { useMongoClient: true } tells moongoose to use the new connection class rather than the old one
For more info click here
Connect to MongoDB with Mongoose 4.11.x (tested with both mLab single instance and MongoDB Atlas replica set):
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const options = {
promiseLibrary: global.Promise,
useMongoClient: true,
};
function connect() {
mongoose.connect(URI, options)
.then(function() {
const admin = new mongoose.mongo.Admin(mongoose.connection.db);
admin.buildInfo(function(err, info) {
if (err) {
console.err(`Error getting MongoDB info: ${err}`);
} else {
console.log(`Connection to MongoDB (version ${info.version}) opened successfully!`);
}
});
})
.catch((err) => console.error(`Error connecting to MongoDB: ${err}`));
}
module.exports = connect;
Create model:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({...});
module.exports = mongoose.model('User', userSchema);
According to the mongoose documentation, this is how useMongoClient can be set.
function connectDatabase(databaseUri){
var promise = mongoose.connect('mongodb://localhost/myapp', {
useMongoClient: true,
});
return promise;
}
The easiest fix for this:
Run this command in project root folder via terminal:
npm remove mongoose
npm install mongoose#4.10.8 --save
Problem solved.
Upgrading is not always the best option.
https://github.com/Automattic/mongoose/issues/5399
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/starbucks', {
useMongoClient: true
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('openUri', function() {
// we're connected!
});
Error:
(node:1652) DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using connect() or createConnection().
Solution: To set useMongoClient:true in connection property
var promise = mongoose.connect('mongodb://localhost/myapp', {
useMongoClient: true,
/* other options */
});
See http://mongoosejs.com/docs/connections.html#use-mongo-client
now listening for request
It works for me using Typescript:
var dbOpt : any = {
useMongoClient: true
}
mongoose.connect(dbURI, dbOpt);
Upgrade mongoose , first you need to uninstall it with this code:
npm uninstall mongoose
Then install it again with the following code :
npm install mongoose --save
Related
I'm doing a Node.js project that contains sub projects. One sub project will have one Mongodb database and Mongoose will be use for wrapping and querying db. But the problem is
Mongoose doesn't allow to use multiple databases in single mongoose instance as the models are build on one connection.
To use multiple mongoose instances, Node.js doesn't allow multiple module instances as it has caching system in require(). I know disable module caching in Node.js but I think it is not the good solution as it is only need for mongoose.
I've tried to use createConnection() and openSet() in mongoose, but it was not the solution.
I've tried to deep copy the mongoose instance (http://blog.imaginea.com/deep-copy-in-javascript/) to pass new mongoose instances to the sub project, but it throwing RangeError: Maximum call stack size exceeded.
I want to know is there anyways to use multiple database with mongoose or any workaround for this problem? Because I think mongoose is quite easy and fast. Or any other modules as recommendations?
According to the fine manual, createConnection() can be used to connect to multiple databases.
However, you need to create separate models for each connection/database:
var conn = mongoose.createConnection('mongodb://localhost/testA');
var conn2 = mongoose.createConnection('mongodb://localhost/testB');
// stored in 'testA' database
var ModelA = conn.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testA database' }
}));
// stored in 'testB' database
var ModelB = conn2.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testB database' }
}));
I'm pretty sure that you can share the schema between them, but you have to check to make sure.
Pretty late but this might help someone. The current answers assumes you are using the same file for your connections and models.
In real life, there is a high chance that you are splitting your models into different files. You can use something like this in your main file:
mongoose.connect('mongodb://localhost/default');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('connected');
});
which is just how it is described in the docs. And then in your model files, do something like the following:
import mongoose, { Schema } from 'mongoose';
const userInfoSchema = new Schema({
createdAt: {
type: Date,
required: true,
default: new Date(),
},
// ...other fields
});
const myDB = mongoose.connection.useDb('myDB');
const UserInfo = myDB.model('userInfo', userInfoSchema);
export default UserInfo;
Where myDB is your database name.
One thing you can do is, you might have subfolders for each projects. So, install mongoose in that subfolders and require() mongoose from own folders in each sub applications. Not from the project root or from global. So one sub project, one mongoose installation and one mongoose instance.
-app_root/
--foo_app/
---db_access.js
---foo_db_connect.js
---node_modules/
----mongoose/
--bar_app/
---db_access.js
---bar_db_connect.js
---node_modules/
----mongoose/
In foo_db_connect.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/foo_db');
module.exports = exports = mongoose;
In bar_db_connect.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/bar_db');
module.exports = exports = mongoose;
In db_access.js files
var mongoose = require("./foo_db_connect.js"); // bar_db_connect.js for bar app
Now, you can access multiple databases with mongoose.
As an alternative approach, Mongoose does export a constructor for a new instance on the default instance. So something like this is possible.
var Mongoose = require('mongoose').Mongoose;
var instance1 = new Mongoose();
instance1.connect('foo');
var instance2 = new Mongoose();
instance2.connect('bar');
This is very useful when working with separate data sources, and also when you want to have a separate database context for each user or request. You will need to be careful, as it is possible to create a LOT of connections when doing this. Make sure to call disconnect() when instances are not needed, and also to limit the pool size created by each instance.
Mongoose and multiple database in single node.js project
use useDb to solve this issue
example
//product databse
const myDB = mongoose.connection.useDb('product');
module.exports = myDB.model("Snack", snackSchema);
//user databse
const myDB = mongoose.connection.useDb('user');
module.exports = myDB.model("User", userSchema);
A bit optimized(for me atleast) solution. write this to a file db.js and require this to wherever required and call it with a function call and you are good to go.
const MongoClient = require('mongodb').MongoClient;
async function getConnections(url,db){
return new Promise((resolve,reject)=>{
MongoClient.connect(url, { useUnifiedTopology: true },function(err, client) {
if(err) { console.error(err)
resolve(false);
}
else{
resolve(client.db(db));
}
})
});
}
module.exports = async function(){
let dbs = [];
dbs['db1'] = await getConnections('mongodb://localhost:27017/','db1');
dbs['db2'] = await getConnections('mongodb://localhost:27017/','db2');
return dbs;
};
I have been using this method and it works great for me until now.
const mongoose = require('mongoose');
function makeNewConnection(uri) {
const db = mongoose.createConnection(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
db.on('error', function (error) {
console.log(`MongoDB :: connection ${this.name} ${JSON.stringify(error)}`);
db.close().catch(() => console.log(`MongoDB :: failed to close connection ${this.name}`));
});
db.on('connected', function () {
mongoose.set('debug', function (col, method, query, doc) {
console.log(`MongoDB :: ${this.conn.name} ${col}.${method}(${JSON.stringify(query)},${JSON.stringify(doc)})`);
});
console.log(`MongoDB :: connected ${this.name}`);
});
db.on('disconnected', function () {
console.log(`MongoDB :: disconnected ${this.name}`);
});
return db;
}
// Use
const db1 = makeNewConnection(MONGO_URI_DB1);
const db2 = makeNewConnection(MONGO_URI_DB2);
module.exports = {
db1,
db2
}
Now, I am trying to develop the transaction session for MongoDB.
MongoDB version: 4.4.2
Mongoose version: 5.11.4
The transaction code
const session = await mongoose.startSession();
session.startTransaction();
try {
const result = await storage.create([attachment], { session: session });
await req.files.newFile.mv(attachment.filePath);
await session.commitTransaction();
return res.send(result);
} catch (err) {
console.log(err);
await session.abortTransaction();
return res.status(500).send(err);
} finally {
session.endSession();
}
When I called this code, that gave me the below error message.
MongoError: This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.
So, I add retryWrites=false code in the mongoose connection code.
AS IS
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
poolSize: 10,
});
TO BE
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
retryWrites: false,
poolSize: 10,
});
But I still have the same problem...
I am not sure what is the problem.
Please MongoDB expert let me know the solution.
See Requirements for using MongoDB transactions for transaction requirements. You are probably using a standalone deployment.
Connecting with MongoDB native driver
I wrote following code to connect mongodb through native driver which has been install with npm install mongodb --save
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://127.0.0.1:27017";
const dbName = "game-of-thrones";
let db;
MongoClient.connect(
url,
{ useNewUrlParser: true },
(err, client) => {
if (err) return console.log(err);
db = client.db(dbName);
console.log(`Connected MongoDB: ${url}`);
console.log(`Database: ${dbName}`);
}
);
When I write on the terminal node server.js I got following error
(node:3500) 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 MongoClient.connect.
Connected MongoDB: mongodb://127.0.0.1:27017
Database: game-of-thrones
The database is connected, but how can I get rid out from the warning
Check your mongo version
mongo --version
If you are using version >= 3.1.0 change you mongo connection file to ->
MongoClient.connect("mongodb://localhost:27017/YourDB", {
useNewUrlParser: true,
useUnifiedTopology: true
})
For details about the useUnifiedTopology option added in 3.2.1, see https://github.com/mongodb/node-mongodb-native/releases/tag/v3.2.1
My advice is to leave it as it is (maybe place a warning). The useUnifiedTopology: true option does not work correctly.
More precisely, in the event of a loss of connection to the DBMS, it will never be restored. Current version 3.3.3 does not solve this problem.
Check this
I got the same error and resolved using the below template.
var MongoClient = require('mongodb').MongoClient
const client = new MongoClient(uri, {useUnifiedTopology: true});
client.connect().then((client)=>{
var db = client.db('db_name')
db.collection('collection_name').find().toArray(function (err, result) {
if (err) throw err
console.log(result);
})
})
This worked for me. and now it's not showing any DepricationWarning.
I want to add to this thread that it may also have to do with other dependencies.
For instance, nothing I updated or set for NodeJS, MongoDB or Mongoose were the issue - however - connect-mongodb-session had been updated and starting slinging the same error. The solution, in this case, was to simply rollback the version of connect-mongodb-session from version 2.3.0 to 2.2.0.
UPDATE: The issue is now fixed in connect-mongodb-session#2.3.1.
This is what made it work for me.
MongoClient.connect('mongodb://localhost:27017/blogdb', {useUnifiedTopology: true} , (err, client) =>
{
if (err) throw err;
const db = client.db('blogdb');
const collection = db.collection('posts');
const users = db.collection('users');
app.locals.collection = collection;
app.locals.users = users;
});
This is the same exact code I had before where I was getting the same deprecation message. The only difference is I haven't added the 'useUnifiedTopology: true' line.
MongoClient.connect('mongodb://localhost:27017/blogdb', (err, client) =>
{
if (err) throw err;
const db = client.db('blogdb');
const collection = db.collection('posts');
const users = db.collection('users');
app.locals.collection = collection;
app.locals.users = users;
});
yeah i got the same issue , the database was connected successfully but i used to face with warning message of deprecating warning. here are some short tips i used to handle it i hope it will help you
mongoose.connect(
database,
{useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
Replace yourdbname with your variable or just link of your mongodb..
mongoose.connect(yourdbname, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
.then(console.log("mongodb connected successfully...."))
.catch(err =>console.log(err));
This is the code I use to connect to my database:
private connectDatabase(databaseUri: string): Promise<Mongoose.Connection> {
return Mongoose.connect(databaseUri).then(() => {
debug('Connected to MongoDB at %O', databaseUri);
return Mongoose.connection;
});
}
Today I updated Mongoose to version 4.11.0 and I got this warning when running my tests:
(node:4138) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using `connect()`
or `createConnection()`
I can't find any information on how to "set useMongoClient".
Do you guys know how to?
This is how you use useMongoClient:
mongoose.connect('mongodb://localhost/advisorDemoTestDB', { useMongoClient: true })
Add { useMongoClient: true } as another argument to connect or createConnection method, its depends on version of mongoose you are using.
// Using `mongoose.connect`...
var promise = mongoose.connect('mongodb://localhost/myapp', {
useMongoClient: true,
/* other options */
});
// Or `createConnection`
var promise = mongoose.createConnection('mongodb://localhost/myapp', {
useMongoClient: true,
/* other options */
});
mongoose.connection.openUri('mongodb://127.0.0.1/camp_v12')
has anyone tried this? my deprecated warning disappeared when i use this, it was from the documentation
http://mongoosejs.com/docs/connections.html
The easiest fix for this would be to open your terminal, change your directory to your root project (folder where package.json is)
Run:
npm remove mongoose
then:
npm install mongoose#4.10.8 --save
problem solved.
Upgrading is not always the best option.
http://mongoosejs.com/docs/connections.html
Without Typescript you can pretty much ignore the issue and use Mongoose.connect(databaseUri, { useMongoClient: true }).
If you really want to avoid having the warning avoid the version 4.11.0.
I updated to version 4.11.1 and since #types/mongoose#4.7.18 are not yet updated and they do not mention the field useMongoClient in the ConnectionOptions, this is how i imported the module:
const Mongoose = require('mongoose');
And then used this function:
private connectDatabase(databaseUri: string): Promise<any> {
return Mongoose.connect(databaseUri, { useMongoClient: true })
.then(() => {
console.log('Connected to MongoDB at ', databaseUri);
return Mongoose.connection;
})
.catch(err => debug(`Database connection error: ${err.message}`));
}
As many answers say, adding { useMongoClient: true } in options argument to connect or createConnection method will solve the problem.
For e.g.
// With mongoose.connect method
mongoose.connect('mongodb://localhost/app', { useMongoClient: true });
// With createConnection method
mongoose.createConnection('mongodb://localhost/app', { useMongoClient: true });
But what is MongoClient in the first place?
From MongoDB Node.js Driver version 1.2, a new connection class MongoClient was introduced that has the same name across all the official drivers.
The new connection class MongoClient acknowledges all writes to MongoDB, in contrast to the existing DB connection class which has acknowledgements turned off.
So { useMongoClient: true } tells moongoose to use the new connection class rather than the old one
For more info click here
Connect to MongoDB with Mongoose 4.11.x (tested with both mLab single instance and MongoDB Atlas replica set):
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const options = {
promiseLibrary: global.Promise,
useMongoClient: true,
};
function connect() {
mongoose.connect(URI, options)
.then(function() {
const admin = new mongoose.mongo.Admin(mongoose.connection.db);
admin.buildInfo(function(err, info) {
if (err) {
console.err(`Error getting MongoDB info: ${err}`);
} else {
console.log(`Connection to MongoDB (version ${info.version}) opened successfully!`);
}
});
})
.catch((err) => console.error(`Error connecting to MongoDB: ${err}`));
}
module.exports = connect;
Create model:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({...});
module.exports = mongoose.model('User', userSchema);
According to the mongoose documentation, this is how useMongoClient can be set.
function connectDatabase(databaseUri){
var promise = mongoose.connect('mongodb://localhost/myapp', {
useMongoClient: true,
});
return promise;
}
The easiest fix for this:
Run this command in project root folder via terminal:
npm remove mongoose
npm install mongoose#4.10.8 --save
Problem solved.
Upgrading is not always the best option.
https://github.com/Automattic/mongoose/issues/5399
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/starbucks', {
useMongoClient: true
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('openUri', function() {
// we're connected!
});
Error:
(node:1652) DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using connect() or createConnection().
Solution: To set useMongoClient:true in connection property
var promise = mongoose.connect('mongodb://localhost/myapp', {
useMongoClient: true,
/* other options */
});
See http://mongoosejs.com/docs/connections.html#use-mongo-client
now listening for request
It works for me using Typescript:
var dbOpt : any = {
useMongoClient: true
}
mongoose.connect(dbURI, dbOpt);
Upgrade mongoose , first you need to uninstall it with this code:
npm uninstall mongoose
Then install it again with the following code :
npm install mongoose --save
I'm doing a Node.js project that contains sub projects. One sub project will have one Mongodb database and Mongoose will be use for wrapping and querying db. But the problem is
Mongoose doesn't allow to use multiple databases in single mongoose instance as the models are build on one connection.
To use multiple mongoose instances, Node.js doesn't allow multiple module instances as it has caching system in require(). I know disable module caching in Node.js but I think it is not the good solution as it is only need for mongoose.
I've tried to use createConnection() and openSet() in mongoose, but it was not the solution.
I've tried to deep copy the mongoose instance (http://blog.imaginea.com/deep-copy-in-javascript/) to pass new mongoose instances to the sub project, but it throwing RangeError: Maximum call stack size exceeded.
I want to know is there anyways to use multiple database with mongoose or any workaround for this problem? Because I think mongoose is quite easy and fast. Or any other modules as recommendations?
According to the fine manual, createConnection() can be used to connect to multiple databases.
However, you need to create separate models for each connection/database:
var conn = mongoose.createConnection('mongodb://localhost/testA');
var conn2 = mongoose.createConnection('mongodb://localhost/testB');
// stored in 'testA' database
var ModelA = conn.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testA database' }
}));
// stored in 'testB' database
var ModelB = conn2.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testB database' }
}));
I'm pretty sure that you can share the schema between them, but you have to check to make sure.
Pretty late but this might help someone. The current answers assumes you are using the same file for your connections and models.
In real life, there is a high chance that you are splitting your models into different files. You can use something like this in your main file:
mongoose.connect('mongodb://localhost/default');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('connected');
});
which is just how it is described in the docs. And then in your model files, do something like the following:
import mongoose, { Schema } from 'mongoose';
const userInfoSchema = new Schema({
createdAt: {
type: Date,
required: true,
default: new Date(),
},
// ...other fields
});
const myDB = mongoose.connection.useDb('myDB');
const UserInfo = myDB.model('userInfo', userInfoSchema);
export default UserInfo;
Where myDB is your database name.
One thing you can do is, you might have subfolders for each projects. So, install mongoose in that subfolders and require() mongoose from own folders in each sub applications. Not from the project root or from global. So one sub project, one mongoose installation and one mongoose instance.
-app_root/
--foo_app/
---db_access.js
---foo_db_connect.js
---node_modules/
----mongoose/
--bar_app/
---db_access.js
---bar_db_connect.js
---node_modules/
----mongoose/
In foo_db_connect.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/foo_db');
module.exports = exports = mongoose;
In bar_db_connect.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/bar_db');
module.exports = exports = mongoose;
In db_access.js files
var mongoose = require("./foo_db_connect.js"); // bar_db_connect.js for bar app
Now, you can access multiple databases with mongoose.
As an alternative approach, Mongoose does export a constructor for a new instance on the default instance. So something like this is possible.
var Mongoose = require('mongoose').Mongoose;
var instance1 = new Mongoose();
instance1.connect('foo');
var instance2 = new Mongoose();
instance2.connect('bar');
This is very useful when working with separate data sources, and also when you want to have a separate database context for each user or request. You will need to be careful, as it is possible to create a LOT of connections when doing this. Make sure to call disconnect() when instances are not needed, and also to limit the pool size created by each instance.
Mongoose and multiple database in single node.js project
use useDb to solve this issue
example
//product databse
const myDB = mongoose.connection.useDb('product');
module.exports = myDB.model("Snack", snackSchema);
//user databse
const myDB = mongoose.connection.useDb('user');
module.exports = myDB.model("User", userSchema);
A bit optimized(for me atleast) solution. write this to a file db.js and require this to wherever required and call it with a function call and you are good to go.
const MongoClient = require('mongodb').MongoClient;
async function getConnections(url,db){
return new Promise((resolve,reject)=>{
MongoClient.connect(url, { useUnifiedTopology: true },function(err, client) {
if(err) { console.error(err)
resolve(false);
}
else{
resolve(client.db(db));
}
})
});
}
module.exports = async function(){
let dbs = [];
dbs['db1'] = await getConnections('mongodb://localhost:27017/','db1');
dbs['db2'] = await getConnections('mongodb://localhost:27017/','db2');
return dbs;
};
I have been using this method and it works great for me until now.
const mongoose = require('mongoose');
function makeNewConnection(uri) {
const db = mongoose.createConnection(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
db.on('error', function (error) {
console.log(`MongoDB :: connection ${this.name} ${JSON.stringify(error)}`);
db.close().catch(() => console.log(`MongoDB :: failed to close connection ${this.name}`));
});
db.on('connected', function () {
mongoose.set('debug', function (col, method, query, doc) {
console.log(`MongoDB :: ${this.conn.name} ${col}.${method}(${JSON.stringify(query)},${JSON.stringify(doc)})`);
});
console.log(`MongoDB :: connected ${this.name}`);
});
db.on('disconnected', function () {
console.log(`MongoDB :: disconnected ${this.name}`);
});
return db;
}
// Use
const db1 = makeNewConnection(MONGO_URI_DB1);
const db2 = makeNewConnection(MONGO_URI_DB2);
module.exports = {
db1,
db2
}