Home >Web Front-end >JS Tutorial >How Can I Efficiently Share Database Connections Across Node.js Modules?
Maintaining a consistent database connection is crucial for seamless operation of Node.js applications. To avoid the need to re-establish connections multiple times, it's essential to implement a strategy that ensures connection sharing across different modules.
The approach described in the original query, involving the creation of a central object that manages database connections and their distribution to modules, is flawed. Instead, it's recommended to employ a module-based solution.
This module acts as a centralized repository for database connection management. It defines functions for both establishing the connection to MongoDB and retrieving the database instance.
const MongoClient = require( 'mongodb' ).MongoClient; const url = "mongodb://localhost:27017"; var _db; module.exports = { connectToServer: function( callback ) { MongoClient.connect( url, { useNewUrlParser: true }, function( err, client ) { _db = client.db('test_db'); return callback( err ); } ); }, getDb: function() { return _db; } };
In the main application file, app.js, the mongoUtil module is imported and the connectToServer function is invoked to establish the database connection.
var mongoUtil = require( 'mongoUtil' ); mongoUtil.connectToServer( function( err, client ) { if (err) console.log(err); // start the rest of your app here } );
In other modules or files, the mongoUtil module can be imported to retrieve the shared database instance using the getDb function.
var mongoUtil = require( 'mongoUtil' ); var db = mongoUtil.getDb(); db.collection( 'users' ).find();
By leveraging this module-based approach, you ensure that all modules within your application have access to a single, shared database connection, without the need for multiple connections and potential inconsistencies.
The above is the detailed content of How Can I Efficiently Share Database Connections Across Node.js Modules?. For more information, please follow other related articles on the PHP Chinese website!