Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-11-19 03:42:02
Original
666 people have browsed it

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
  });
Copy after login

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

  const _db = global.mongoDB;

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

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
  });
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template