How to Properly Reuse Connection to MongoDB Across NodeJs
Last Updated :
19 Mar, 2024
Efficiently managing database connections is important for Node.js applications using MongoDB. MongoDB connection reuse in Node.js is a practice that optimizes resource utilization and enhances application performance.
By reusing connections, developers can reduce the overhead associated with establishing new connections for each database interaction, especially in high-traffic applications.
In this article, We will explore various methods of easily reusing MongoDB connections across routes in Node.js projects with the help of examples and so on.
How to Efficiently Manage MongoDB Connections Across Routes in a Node.js
Properly reusing connections to MongoDB across Node.js applications and modules is essential for optimizing performance and resource utilization. This practice involves establishing a single database connection that is shared and reused throughout the application's lifecycle.
To achieve this Below are the approach or methods that help us are as follows:
- Dedicated Connection Pool (Using MongoClient)
- Mongoose (ODM Library)
1. Dedicated Connection Pool (Using MongoClient)
When a driver initializes, a new connection pool is generated, acting as a repository for pre-established connections, all managed by the database driver (a ). Whenever our Node.js application requires database interaction, it retrieves a connection from the pool, executes the operation, and automatically returns it to the pool.
These pools are thread-safe, ensuring smooth concurrent access to the MongoDB database. Since a connection pool is created only once, it also helps reduce application latency.
Before going into code, here are the steps to create a project.
Step 1: Create a folder named 'node_app'.
mkdir node_app
Step 2: Go to that folder using the cd command.
cd node_app
Step 3: Create a new Node.js Project.
npm init -y
Step 4: Install MongoDB driver:
npm install mongodb
package.jsonStep 5: create a folder db and inside create connection.js file.
mkdir db
cd db
echo . > connection.js
Step 6: create index.js file in root folder.
echo . > index.js
folder structureStep 7: Add this code in both files.
The below code defines a module that exports a function connectToDb
, which creates and returns a MongoDB client instance. It uses the mongodb
package to connect to a MongoDB database specified by the connection URI (mongodb://localhost:27017
) and database name (university
).
The function also sets the maximum pool size for the connection pool to 10. If a client instance already exists, it reuses it instead of creating a new one.
// File name: db/connection.js
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017'; // MongoDB connection URI
const databaseName = 'university';
let mongoClientInstance = null;
// Setting the maximum pool size for the connection pool.
let maxPoolSize = 10;
// Object of connection Option
const connectionOption = {
maxPoolSize: maxPoolSize
}
async function connectToDb() {
if (!mongoClientInstance) {
mongoClientInstance = await MongoClient.connect(url, connectionOption);
console.log("Database Connected Successfully")
}
// returning a reference to the database
return mongoClientInstance.db(databaseName);
}
module.exports = { connectToDb };
This index.js
file demonstrates the usage of the connectToDb
function from ./db/connection.js
to establish a connection to a MongoDB database named "university". It then inserts a sample document into a collection named "articles" and fetches documents where the "tags" array includes "NoSQL", converting the result to an array and logging it to the console.
// File name: index.js
const { connectToDb } = require('./db/connection');
async function main() {
const db = await connectToDb();
// Using database instance
const collection = db.collection('articles');
// sample data
const data = {
"title": "Using MongoDB for Efficient Data Storage and Retrieval in Real-world Applications",
"author": "Rizwan Bhavnagri",
"published_date": "2024-03-20",
"content": "MongoDB is a popular NoSQL database that provides a flexible and scalable solution for storing and retrieving data in real-world applications.",
"tags": ["MongoDB", "NoSQL", "Database", "GeeksforGeeks", "Tutorial"]
}
// Insertiing a document
const doc = await collection.insertOne(data);
console.log("Inserted document with _id:", doc.insertedId);
// Fetching and Converting collection to array
const result = await collection.find({ tags: "NoSQL" }).toArray();
console.log(result);
}
main();
Output:
Database Connected Successfully
Inserted document with _id: new ObjectId('65ee028e099a0359d5ed55fd')
[
{
_id: new ObjectId('65ee028e099a0359d5ed55fd'),
title: 'Using MongoDB for Efficient Data Storage and Retrieval in Real-world Applications',
author: 'Rizwan Bhavnagri',
published_date: '2024-03-20',
content: 'MongoDB is a popular NoSQL database that provides a flexible and scalable solution for storing and retrieving data in real-world applications.',
tags: [ 'MongoDB', 'NoSQL', 'Database', 'GeeksforGeeks', 'Tutorial' ]
}
]
Output:
run - node index.jsNote: Here, i had added one document which you can view in MongoDB Compass.
Explanation:
- Firstly, we import MongoClient from MongoDB, which serves as the primary entry point for establishing connections with the MongoDB Server.
- Next, we define the MongoDB connection URI and specify the database name.
- We initialize a MongoClient instance with null and some connection options.
- The connectToDb function is responsible for establishing a connection to the MongoDB Server, returning a database reference.
- In the main function, we retrieve a collection named 'articles' from the database, if it does not exist, it will be automatically created.
- We then insert one document into the 'articles' collection.
- Lastly, we fetch one document and convert it to an array.
2. Using Mongoose Library
Mongoose is a popular Object Data Modelling (ODM) library for node.js with MongoDB, it simplifies data interaction and connection management. Mongoose provide tools to define schemas, perform validations, and execute queries in easy way compared to raw database interactions.
Step 1: Install mongoose library.
npm install mongoose
package.jsonStep 2: Create index.js file
echo . > index.js
folder structureStep 3: Put this code in index.js file.
This below code demonstrates how to connect to a MongoDB database using Mongoose in a Node.js application. It first imports the Mongoose library and defines the MongoDB connection URI. The main
function attempts to establish a connection to the MongoDB database using mongoose.connect
, and logs a success message if the connection is successful. If an error occurs during the connection attempt, it logs the error message.
// File name: index.js
const mongoose = require('mongoose');
// MongoDB connection URI
const mongoURI = 'mongodb://localhost:27017/university';
async function main() {
try {
// Connect to the MongoDB with the connection URI
await mongoose.connect(mongoURI);
console.log('Database connected successfully');
} catch (error) {
console.error('MongoDB connection error:', error);
}
}
main();
Output:
OutputExplanation:
- The mongoose.connect function is called within the main function, where it receives the connection URI as a parameter.
- Error handling for potential connection failures is implemented within a try...catch block.
Conclusion
Overall, Properly managing MongoDB connections across routes in a Node.js project is crucial for optimal performance. Utilizing a dedicated connection pool with MongoClient or leveraging the Mongoose library helps efficiently reuse connections, minimizing latency. These approaches ensure smooth database interactions, enhancing the application's overall performance and reliability.
Similar Reads
How to connect mongodb Server with Node.js ?
mongodb.connect() method is the method of the MongoDB module of the Node.js which is used to connect the database with our Node.js Application. This is an asynchronous method of the MongoDB module. Syntax: mongodb.connect(path,callbackfunction)Parameters: This method accept two parameters as mention
2 min read
How to Connect Node to a MongoDB Database ?
Connecting Node.js to MongoDB is a common task for backend developers working with NoSQL databases. MongoDB is a powerful, flexible, and scalable database that stores data in a JSON-like format. In this step-by-step guide, we'll walk through the entire process from setting up your development enviro
6 min read
How to Check the Correct Number of Connections to MongoDB?
Monitoring and managing database connections is crucial for maintaining the performance and stability of MongoDB deployments. In this article, we'll explore how to check the correct number of connections to MongoDB by covering concepts, tools, and practical examples with outputs to help beginners un
3 min read
How to use MongoDB Connection String
MongoDB connection strings are essential for establishing connections between applications and MongoDB databases. These strings contain crucial information such as server addresses, authentication credentials and optional parameters, enabling seamless communication. Understanding the structure and c
6 min read
How to Handle Lost Connection to Mongodb from Nodejs?
Handling lost connections to MongoDB in a Node.js application is crucial for maintaining application reliability and data integrity. However, network issues, database server crashes, or other unexpected events can cause the connection to be lost. This article will guide you through different approac
3 min read
How to add range in the Collection of Mongodb using Node.js ?
Mongoose.module is one of the most powerful external module of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server.Mongoose module provides several functions in order to manipulate the documen
2 min read
How to rename the collection name of MongoDb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read
How to save connection result in a variable in Node.js ?
We are going to use the query function in MySQL library in node.js that will return our output as expected. Using this approach, we can save connection result in a variable in Node.js. Setting up environment and Execution: Step 1: Initialize node project using the following command. npm init Step 2:
1 min read
How to Connect Node.js To MongoDB Atlas Using Mongoose?
MongoDB Atlas is a cloud-based database service that offers robust features and scalability for managing our data. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple HTML form. In this tutoria
6 min read
How To Handle Global Connection of MongoDB in NodeJs?
Handling a global connection to MongoDB in a Node.js application is important for efficient resource management and performance optimization. By maintaining a single connection to the MongoDB database, you avoid the overhead of repeatedly establishing and closing connections, which can be resource-i
2 min read