Mongoose, One of the best object modeling framework of Node.js and MongoDB, doesn’t have feature to use multiple databases in single project. Again, to use multiple mongoose instances, Node.js only return loaded module instances from it’s caching system on require(). It means second require() for same module loading will only get the same instance. I am not sure about disabling module caching but I think it is not the good solution. But, as a workaround, we can get the separate mongoose instances by installing the module in separate folder and require() from that folders on each db access.
Let’s assume we have two sub components foo and bar in our project. Foo will use foo_db and bar will use bar_db. So the project structure may be like this.
-app_root/
–foo/
—db_access.js
—foo_db_connect.js
—node_modules/
—-mongoose/
–bar/
—db_access.js
—bar_db_connect.js
—node_modules/
—-mongoose/
In foo_db_connect.js
var mongoose = require('./node_modules/mongoose'); mongoose.connect('mongodb://localhost/foo_db'); module.exports = exports = mongoose;
In bar_db_connect.js
var mongoose = require('./node_modules/mongoose'); mongoose.connect('mongodb://localhost/bar_db'); module.exports = exports = mongoose;
In Data access files (db_access.js)
var mongoose = require("./foo_db_connect.js");
Now we can use multiple MongoDB databases with Mongoose.