Mongoose: How to Connect to Self-Hosted MongoDB (3 Examples)

Updated: December 30, 2023 By: Guest Contributor Post a comment

Learn how to connect to your self-hosted MongoDB database with Mongoose.js through basic and advanced practical examples.

Basic Connection

Establishing a simple connection using Mongoose’s connect method.

  1. Install mongoose via npm: npm install mongoose
  2. Import mongoose in your application.
  3. Use the connect method with your MongoDB URI.
  4. Handle the connection events.

Example:

const mongoose = require('mongoose');

mongoose.connect('mongodb://username:password@host:port/database', { useNewUrlParser: true });

mongoose.connection.on('connected', function () {
    console.log('Mongoose default connection open to db');
});

mongoose.connection.on('error', function (err) {
    console.error('Mongoose default connection error: ' + err);
});

This code sets up a connection to a MongoDB database using Mongoose and provides basic logging for connection events and errors. Remember to replace username, password, host, port, and database with your actual MongoDB credentials and details.

Connection with Options

Connecting to MongoDB with additional configuration to handle reconnections, timeouts, etc.

  1. Follow the first three steps as in the Basic Connection.
  2. Add a configuration options object as the second parameter to the connect method.

Example:

const mongoose = require('mongoose');

const options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  connectTimeoutMS: 30000,
  socketTimeoutMS: 45000
};

mongoose.connect('mongodb://username:password@host:port/database', options);

mongoose.connection.on('connected', function () {
    console.log('Mongoose connection open to db with options');
});

mongoose.connection.on('error', function (err) {
    console.error('Mongoose connection error: ' + err);
});

This code sets up a connection to a MongoDB database using Mongoose with additional options for the connection, such as useNewUrlParser, useUnifiedTopology, connectTimeoutMS, and socketTimeoutMS. Make sure to replace username, password, host, port, and database with your actual MongoDB credentials and details.

Connection Pooling

Connection pooling allows you to manage a set of database connections for re-use.

  1. Install and import mongoose as before.
  2. Set the poolSize option in the configuration object.
  3. Use the connect method.

Example:

const mongoose = require('mongoose');
const poolOptions = { poolSize: 10 };

mongoose.connect(
  'mongodb://username:password@host:port/database',
  { ...poolOptions, useNewUrlParser: true, useUnifiedTopology: true }
);

mongoose.connection.on('connected', function () {
  console.log('Mongoose has created a pool of connections');
});

mongoose.connection.on('error', function (err) {
  console.log('Mongoose pool connection error: ' + err);
});

Here’s a breakdown of what each part does:

  1. const mongoose = require('mongoose'); – This line imports the Mongoose library, which provides a straightforward, schema-based solution to model your application data with MongoDB.
  2. const poolOptions = { poolSize: 10 }; – This line defines an options object for the connection pool. The poolSize option sets the maximum number of sockets the MongoDB driver will keep open for this connection.
  3. mongoose.connect(...) – This line establishes a connection to a MongoDB database. The first argument is the connection string, and the second argument is an options object. The useNewUrlParser and useUnifiedTopology options are set to true to use the new URL string parser and the new server discovery and monitoring engine, respectively.
  4. mongoose.connection.on('connected', function () {...}); – This line sets up a listener for the ‘connected’ event, which will be emitted when Mongoose successfully connects to the MongoDB server. When this event is triggered, it logs a message to the console.
  5. mongoose.connection.on('error', function (err) {...}); – This line sets up a listener for the ‘error’ event, which will be emitted if there is an error with the connection. When this event is triggered, it logs the error message to the console.

Pros: Efficient use of database connections for multiple requests.

Cons: Overhead in pool management and the potential for resource exhaustion if not configured correctly.

Final Words

There are multiple ways to connect Mongoose to a self-hosted MongoDB, ranging from simple connections to more advanced techniques that include additional options for fine-tuning the connection and management of connection pools. The choice of implementation depends on individual project needs and should balance the ease of use with the required level of control and scalability.