Sling Academy
Home/Node.js/Mongoose: How to Connect to Self-Hosted MongoDB (3 Examples)

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

Last updated: December 30, 2023

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.

Next Article: How to set up and use Mongoose with TypeScript

Previous Article: Mongoose: How to connect to MongoDB Atlas

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates