Mongoose and multiple database in single node.js project Mongoose and multiple database in single node.js project mongoose mongoose

Mongoose and multiple database in single node.js project


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' databasevar ModelA    = conn.model('Model', new mongoose.Schema({  title : { type : String, default : 'model in testA database' }}));// stored in 'testB' databasevar 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.