Mongoose Connection String Options
Last Updated :
16 May, 2025
Mongoose is a JavaScript library that provides a convenient way to interact with MongoDB databases. One of the critical steps in setting up a MongoDB connection is configuring the Mongoose connection string options, which define how Mongoose interacts with the MongoDB server. This article will help you understand these connection options and how to use them effectively.
What is a Mongoose Connection String?
A Mongoose connection string is a URL-like string that provides all the necessary details required to connect your Node.js application to a MongoDB database. It includes several parameters such as the database name, authentication credentials, and connection options. By understanding and configuring the right connection string options, you ensure a stable and optimized connection to your MongoDB database.
Syntax:
mongoose.connect('<connection-string>', <options>, <callback>);
Connection String Parameters
A typical Mongoose connection string includes the following parameters:
- dbName: The name of the database to connect to.
- user and pass: The username and password to use for authentication.
- host: The hostname or IP address of the MongoDB server.
- port: The port number on which the MongoDB server is listening.
- useNewUrlParser: Set to true to use the new MongoDB connection string parser.
- useUnifiedTopology: Set to true to use the new Server Discovery and Monitoring engine.
- authSource: The name of the database to use for authentication. This is typically the admin database.
- connectTimeoutMS: specifies the time in milliseconds to wait for a connection to be established before timing out.
- socketTimeoutMS: specifies the time in milliseconds to wait for a response from the server before timing out.
- heartbeatFrequencyMS: specifies the frequency in milliseconds to send a server monitoring command to check the health of the server.
- retryWrites: specifies that write operations should be retried once after a network error.
- w: specifies the write concern level for write operations. Here, we are using the majority value to require acknowledgment from a majority of replica set members.
- ssl: Whether to use SSL/TLS for the connection.
- replicaSet: The name of the replica set to connect to.
- readPreference: The read preference mode for the connection.
- writeConcern: The write concern options for the connection.
These options can be passed in as query parameters in the connection string, or they can be specified as an options object passed to the mongoose.connect() method in your Node.js application.
Installating Mongoose
Before connecting to MongoDB, you need to install the Mongoose module. Follow these steps to set up Mongoose in your Node.js application:
Step 1: Install Mongoose
You can install this package by running this command in your project directory
npm install mongoose
Step 2: Verify Installation
After installing the mongoose module, you can check your mongoose version in the command prompt using the command.
npm version mongoose
Step 3: Set Up Your Project
After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.
node index.js
Project Structure: The project structure will look like this:
Example 1: Basic Connection to MongoDB
The below code establishes a connection to a MongoDB database running on localhost with the name Geeksforgeeks. The useNewUrlParser and useUnifiedTopology options are specified to use the new MongoDB connection string parser and Server Discovery and Monitoring engine. The callback function logs a message to the console indicating whether the connection was successful or not.
index.js
JavaScript
const mongoose = require("mongoose");
const connectionStr = "mongodb://localhost:27017/Geeksforgeeks";
mongoose.set("strictQuery", true);
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
mongoose.connect(connectionStr, options, (error, connection) => {
if (error) {
console.error("Error connecting to MongoDB:", error);
} else {
console.log("Connected to MongoDB!");
}
});
Steps to run the application:
Make sure you have installed the mongoose module using the following command:
npm install mongoose
Run the index.js file using the below command:
node index.js
Output:
Example 2: Advanced Connection with Additional Options
In this example, we are using the following Mongoose connection string options: authSource, useNewUrlParser, useUnifiedTopology, connectTimeoutMS, socketTimeoutMS, heartbeatFrequencyMS and retryWrites. If the connection is successful with the given string options then "connected to MongoDB!" will be printed in the console, else error block will run.
index.js
JavaScript
const mongoose = require("mongoose");
const connectionStr =
"mongodb://localhost:27017/Geeksforgeeks";
mongoose.set("strictQuery", true);
const options = {
authSource: "admin",
useNewUrlParser: true,
useUnifiedTopology: true,
connectTimeoutMS: 5000,
socketTimeoutMS: 20000,
heartbeatFrequencyMS: 10000,
retryWrites: true,
w: "majority",
};
mongoose.connect(connectionStr, options,
(error, connection) => {
if (error) {
console.error("Error connecting to MongoDB:", error);
} else {
console.log("Connected to MongoDB!");
}
});
Step to run the application:
- Install the Mongoose module:
npm install mongoose
. - Run the application with:
node index.js
.
Output:
Conclusion:
The Mongoose connection string is a vital component when connecting your Node.js application to MongoDB. By understanding the various Mongoose connection string options, you can optimize your database interactions for performance, reliability, and security. Make sure to choose the right options based on your project’s needs, whether you're working with a simple local database or a more complex production environment with replica sets, authentication, and advanced settings.