0

I'm working on a small project in JS and want to access 2 different mongoose databases. It seems like only one of the databases is being accessed...

Here's my code in app.js:

mongoose.connect('mongodb://someOtherDb', { useNewUrlParser: true, useCreateIndex: true });
const connection = mongoose.connection;
connection.on('open',()=>{
    console.log(" database connected")
})
connection.on('error',()=>{
    console.log("error in connecting to database")
})

mongoose.connect('mongodb://localhost:27017/users', { useNewUrlParser: true, useCreateIndex: true });
const userDb = mongoose.connection;

// on mongo error
userDb.on('error', console.error.bind(console, 'connection error:'));

// sessions for logins
app.use(session({
  secret: 'top secret!',
  saveUninitialized: false,
  resave: true,
  store: new MongoStore({
    mongooseConnection: userDb
  })
}));

Is the problem with the mongoose.connect part and how I set userDb and connection equal to mongoose.connection?

Thanks!

Edwin
  • 380
  • 1
  • 4
  • 18
  • you are creating the second connection on same mongoose object so it will be overwritten with the new one, you need multiple objects for multiple cluster connections. – AZ_ Apr 19 '19 at 05:58

1 Answers1

0

Mongoose handling connections via connections pool http://mongoosejs.com/docs/connections.html

You can use server: {poolSize: 5} option for increase/decrease pool (number of parallel connections)

If you need connections to different databases look here Mongoose and multiple database in single node.js project

Example of multiple connections:

var mongoose = require('mongoose')
var conn1 = mongoose.createConnection('mongodb://someOtherDb');
var conn2 = mongoose.createConnection('mongodb://localhost:27017/users');
var Schema = new mongoose.Schema({})
var model1 = conn1.model('collection1', Schema);
var model2 = conn2.model('collection2', Schema);
model1.find({}, function() {
   console.log("datas found 1");
});
model2.find({}, function() {
   console.log("datas found 2");
});
Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59