Learn how to connect to your self-hosted MongoDB database with Mongoose.js through basic and advanced practical examples.
Table of Contents
Basic Connection
Establishing a simple connection using Mongoose’s connect method.
- Install mongoose via npm:
npm install mongoose
- Import mongoose in your application.
- Use the connect method with your MongoDB URI.
- 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.
- Follow the first three steps as in the Basic Connection.
- 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.
- Install and import mongoose as before.
- Set the poolSize option in the configuration object.
- 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:
const mongoose = require('mongoose');
– This line imports the Mongoose library, which provides a straightforward, schema-based solution to model your application data with MongoDB.const poolOptions = { poolSize: 10 };
– This line defines an options object for the connection pool. ThepoolSize
option sets the maximum number of sockets the MongoDB driver will keep open for this connection.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. TheuseNewUrlParser
anduseUnifiedTopology
options are set totrue
to use the new URL string parser and the new server discovery and monitoring engine, respectively.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.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.