Home > Article > Web Front-end > 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!