177

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?

2
  • this video is a good reference for connecting to multiple databases. Although it's in Hindi, you can follow along with the code in the video.
    – Gangula
    Nov 22, 2022 at 18:36
  • a related question here which talks about the difference between connect and createconnection
    – Gangula
    Nov 22, 2022 at 18:42

7 Answers 7

260

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.

20
  • 5
    Yes, named connections and a shared schema are the way to go I think. Each connection will need a unique model as per Robert's example. Oct 22, 2013 at 6:44
  • 26
    Also checkout useDb() available in 3.8 to share the underlying connection pool: github.com/LearnBoost/mongoose/wiki/… Nov 2, 2013 at 15:21
  • 1
    Suppose I have auto-generated database (Say n number of database). Not one or two. Is there any way to connect to these without creating separate model for each database ? Feb 18, 2015 at 17:53
  • 1
    @AnoojKrishnanG I don't think that's possible, no. You need to create the model against each database separately. However, as I already stated in my answer, you may be able to share the schema's amongst the connections, which may save some coding time.
    – robertklep
    Feb 20, 2015 at 9:52
  • 1
    You can share the schema across the different models, and therefore DBs. var newSchema = new mongoose.Schema({ ... }), var model2 = conn1.model('newModel', newSchema), var model2 = conn2.model('newModel', newSchema)
    – grant
    Dec 6, 2016 at 20:33
94

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.

5
  • 2
    Thank you - I was able to use 3 different databases within a single application using: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const mySchema = new Schema ({}); const mydbvar = mongoose.connection.useDb('mydb') module.exports = mydbvar.model('myCollection', MySchema); Jun 26, 2018 at 14:21
  • 8
    Definitely the best and most real-world example. Connect to the default db (just like if you were using something like SQL Server) and then take advantage of useDb to target your DML at the appropriate database. (Very helpful for keeping your users in one db and your data in another.) No need to start making multiple connections when ultimately you are sending requests to the same server. Now, if you were connecting to two different servers, that's a different kettle of fish.
    – Newclique
    Sep 10, 2018 at 21:01
  • 3
    As @Wade said, as far as I understand this solution only works when all of the databases are on the same server. It's not clear if this answers the OP's question and IMO is a bit misleading.
    – joniba
    Jan 15, 2019 at 16:31
  • This is just what I needed for MongoDB Atlas migration from test, and also to avoid having multiple connections. However, I also .db at the end (const v1 = mongoose.connection.useDb('test').db) as the old db doesn't need to be mongoose managed.
    – Polv
    Jul 26, 2020 at 9:48
  • Seems great when db's are in the same server... Is there a similar approach when db's are in differents hosts?
    – Miquel
    Jan 16, 2022 at 17:45
50

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.

6
  • 4
    This means that every project will have its own connection. You will not be able to manage 100k connections. I think it would be better to use useDb command which uses the same connection pool.
    – xpepermint
    Nov 29, 2015 at 9:49
  • 1
    xpepermint are you able to show an example for useDb -- I am having this issue currently stackoverflow.com/questions/37583198/…
    – Lion789
    Jun 2, 2016 at 7:15
  • 4
    This looks like a huge burden on the project. don't you think so? Aug 2, 2016 at 1:44
  • 1
    Having a few different connection instances (e.g. for a User DB, a Session DB, and for application data) per application is absolutely fine. It's not 'a huge burden' or going to cause scaling problems and is a common use case. Jul 25, 2017 at 15:44
  • You are the best my friend! thanks so much! it works for me! thanks! Feb 13, 2019 at 19:29
47

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.

6
  • 1
    is this another way to writing 'Above Answer' ?
    – pravin
    Oct 3, 2016 at 18:12
  • 18
    This is not the above answer, it's better. The above answer installs multiple copies of Mongoose, unnecessarily. Aug 10, 2017 at 9:07
  • how would i make queries using this method?
    – shahidfoy
    Nov 20, 2018 at 20:44
  • 3
    await instance1.connection.collection('foo').insert({ foo: 'bar', }) await instance2.connection.collection('foo').insert({ foo: 'zoo', }) Jul 26, 2019 at 7:37
  • In fact better working in my case since I have completely different credentials for each connection, let alone models and databases.
    – tzn
    Aug 2, 2020 at 16:24
6

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);
1
  • 1
    This should be the best solution. Utilize one connection to access multiple database
    – Jovanni G
    Nov 6, 2021 at 1:54
2

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;
    };
1
  • how can I create a modal using this way ? May 2, 2021 at 13:37
1

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.