Home  >  Article  >  Web Front-end  >  How Can I Efficiently Reuse MongoDB Connections in My Node.js Application?

How Can I Efficiently Reuse MongoDB Connections in My Node.js Application?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-19 03:42:02667browse

How Can I Efficiently Reuse MongoDB Connections in My Node.js Application?

Reusing MongoDB Connections in Node.js Applications

Reusing MongoDB connections across different modules and throughout the application's lifecycle is crucial for performance optimization. Below is a recommended approach to achieve this:

In your server.js file, initialize a MongoDB connection and store it in a global shared object, accessible across modules:

  const MongoClient = require('mongodb').MongoClient;
  const url = "mongodb://localhost:27017";

  MongoClient.connect(url, (err, client) => {
    if (err) {
      console.log("Error connecting to MongoDB", err);
      return;
    }

    const db = client.db('test_db');
    global.mongoDB = db; // Making the connection available globally
  });

Create a separate module, such as mongoUtil.js, to encapsulate the connection logic:

  const _db = global.mongoDB;

  module.exports = {
    getDb: () => _db,
  };

In your other modules, you can use the mongoUtil module to access the database:

  const mongoUtil = require('./mongoUtil');
  const db = mongoUtil.getDb();

  db.collection('users').find((err, result) => {
    // Use the result
  });

This approach ensures that a single connection is established and shared across the application, optimizing performance and avoiding multiple simultaneous connections to the database.

The above is the detailed content of How Can I Efficiently Reuse MongoDB Connections in My Node.js Application?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn