How to use multiple database in a single Node.js project with Mongoose?

Sometimes, we want to use multiple database in a single Node.js project with Mongoose.

In this article, we’ll look at how to use multiple database in a single Node.js project with Mongoose.

How to use multiple database in a single Node.js project with Mongoose?

To use multiple database in a single Node.js project with Mongoose, we can use the connection’s model method.

For instance, we write

const conn = mongoose.createConnection('mongodb://localhost/testA');
const conn2 = mongoose.createConnection('mongodb://localhost/testB');

const ModelA = conn.model('Model', new mongoose.Schema({
  title: {
    type: String,
    default: 'model in testA database'
  }
}));

const ModelB = conn2.model('Model', new mongoose.Schema({
  title: {
    type: String,
    default: 'model in testB database'
  }
}));

to call mongoose.createConnection to connect to 2 databases.

Then we call model on each to create 2 models from 2 different connections and 2 different schemas.

We add the title property to each schema with type String.

Conclusion

To use multiple database in a single Node.js project with Mongoose, we can use the connection’s model method.