Open In App

Mongoose Connection String Options

Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose is a JavaScript library that provides a convenient way to interact with MongoDB databases. In order to use Mongoose, you need to create a connection between your Node.js application and the MongoDB server. The Mongoose connection represents this connection and provides a number of useful features, such as connection pooling and events for monitoring the connection status.

Syntax:

mongoose.connect('<connection-string>', <options>, <callback>);

Parameters: A Mongoose connection string is a URL-like string that contains all the information needed to connect to a MongoDB database using Mongoose. 

 

It typically 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.

Installation of mongoose module:

Step 1: You can install this package by using this command.

npm install mongoose

Step 2: After installing the mongoose module, you can check your mongoose version in the command prompt using the command.

npm version mongoose

Step 3: 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: 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: Run the index.js file using the below command:

Step 1:  Make sure you have installed the mongoose module using the following command:

npm install mongoose

Step 2: Run the index.js file using the below command:

node index.js

Output:

 

Example 2: In this example, we are using the following Mongoose connection string options: authSource, useNewUrlParser, useUnifiedTopology, connectTimeoutMS, socketTimeoutMS, heartbeatFrequencyMS, retryWrites, w.

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 = 
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: Run the index.js file using the below command:

node index.js

Output:

 



Last Updated : 09 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads