MongooseError: You can not `mongoose.connect()` multiple times while connected
In order to use multiple MongoDB connections use mongoose.createConnection
function instead of mongoose.connect
.
mongoose.createConnection
Will give you a connection object which you can further use in your model file, Cause models are always bound to a single connection
let config = require('../config');
let mongoose = require('mongoose');
exports.connect = function () {
const db = mongoose.createConnection(config.mongoUrl, {
reconnectInterval: 5000,
reconnectTries: 60
// add more config if you need
});
db.on(`error`, console.error.bind(console, `connection error:`));
db.once(`open`, function () {
// we`re connected!
console.log(`MongoDB connected on " ${config.mongoUrl}`);
});
};
I've had the same problem and solved pretty easily. All i had to do was to remove any connections in my controllers.
Before: Server.js
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost:27017/DB';
mongoose.connect(connectionString);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
//Server code...
Controller.js
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost:27017/DB';
mongoose.connect(connectionString);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
//Controller code...
After: Server.js
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost:27017/DB';
mongoose.connect(connectionString);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
//Server code...
Controller.js
//Controller code...
Obviously I removed it from all my controller files.
In mongoose version 5.6.1 the check was added https://github.com/Automattic/mongoose/pull/7905
Revert to an older version for a quick fix.