Skip to main content

Multiple Connections in Mongoose

Multiple Connections in Mongoose | Rustcode

Managing Multiple Connections in Mongoose

In some applications, you may need to connect to multiple MongoDB databases or multiple MongoDB clusters simultaneously. Mongoose supports this via its createConnection() method that allows you to establish and manage multiple distinct connections.


Using mongoose.createConnection()

Unlike mongoose.connect(), which sets up a default connection, createConnection() returns a separate connection instance. You can use this instance to define models and perform operations independently.

const mongoose = require('mongoose');

const conn1 = mongoose.createConnection('mongodb://localhost:27017/dbOne', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const conn2 = mongoose.createConnection('mongodb://localhost:27017/dbTwo', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// Define models on each connection separately
const User = conn1.model('User', userSchema);
const Product = conn2.model('Product', productSchema);
  

Using multiple connections allows finer control when working with different databases or clusters.


When to Use Multiple Connections

  • Connecting to multiple databases within the same app.
  • Separating concerns by database or service.
  • Working with different MongoDB clusters or cloud providers.

Connection Lifecycle Management

Each connection instance acts independently; you must manage events like open, error, and closing for each connection.

conn1.on('open', () => {
  console.log('Connection 1 is open');
});

conn2.on('error', (err) => {
  console.error('Connection 2 error:', err);
});
  

Summary Table

Feature Description Notes
mongoose.connect() Creates a default, global connection Used when connecting to a single database
mongoose.createConnection() Creates distinct connection instances Use for multiple DBs or clusters
Model binding Models bind to a specific connection Define models per connection instance

Best Practices

  • Use createConnection() when working with multiple databases or clusters.
  • Manage event listeners for each connection instance.
  • Keep model definitions scoped to their respective connections.
  • Close connections properly when they are no longer needed.

Conclusion

Mongoose's support for multiple connections provides flexibility for complex applications requiring access to multiple MongoDB databases or clusters. Proper management of these connections and their models ensures robust and maintainable data handling.

Comments