Node.js中基于Redis配置实现MongoDB多库单例连接方案问询
Hey there! Let's build out your dbConnection.js properly to meet your requirements: fetching MongoDB config from Redis, creating a singleton connection, and handling all async logic cleanly.
Full Implementation
const { MongoClient } = require('mongodb'); const redis = require('redis'); const { promisify } = require('util'); // Initialize Redis client (adjust Redis config as per your setup) const redisClient = redis.createClient({ host: 'localhost', // your Redis host port: 6379 // your Redis port }); // Promisify Redis get method for async/await usage const getRedisConfig = promisify(redisClient.get).bind(redisClient); // Singleton MongoDB connection instance let dbInstance = null; /** * Fetch MongoDB config from Redis and create a singleton connection * @returns {Promise<MongoClient>} MongoDB database instance */ async function getMongoConnection() { // Check if we already have a valid connected instance if (dbInstance && dbInstance.topology.isConnected()) { console.log('Reusing existing MongoDB connection'); return dbInstance; } try { // Step 1: Fetch MongoDB config from Redis // Assuming you've stored the config as a JSON string in Redis with key "mongodb_config" const configJson = await getRedisConfig('mongodb_config'); if (!configJson) { throw new Error('MongoDB config not found in Redis'); } const mongoConfig = JSON.parse(configJson); const { username, password, host, port, dbName } = mongoConfig; // Step 2: Build MongoDB connection string let connectionString; if (username && password) { connectionString = `mongodb://${username}:${encodeURIComponent(password)}@${host}:${port}/${dbName}?authSource=admin`; } else { connectionString = `mongodb://${host}:${port}/${dbName}`; } // Step 3: Create new MongoDB connection const client = await MongoClient.connect(connectionString, { useNewUrlParser: true, useUnifiedTopology: true }); dbInstance = client.db(dbName); console.log('New MongoDB connection established'); return dbInstance; } catch (error) { console.error('Failed to connect to MongoDB:', error); throw error; // Re-throw to let caller handle the error } } // Optional: Method to reset the singleton instance (useful if config changes in Redis) function resetMongoConnection() { if (dbInstance) { dbInstance.client.close(); dbInstance = null; console.log('MongoDB connection reset'); } } module.exports = { getMongoConnection, resetMongoConnection };
Key Details Explained
- Singleton Pattern: We use the
dbInstancevariable to store the active connection. Every call togetMongoConnection()first checks if this instance exists and is connected—if so, it returns the existing one instead of creating a new connection. - Redis Config Fetch: We promisify Redis's
getmethod to use async/await, making the code easier to read. We assume your MongoDB config is stored as a JSON string in Redis (e.g.,SET mongodb_config '{"username":"admin","password":"secret","host":"localhost","port":27017,"dbName":"mydb"}'). - Connection String Handling: We handle both authenticated and unauthenticated MongoDB setups, using
encodeURIComponent()to safely escape special characters in the password. - Error Handling: Proper try/catch blocks catch issues with Redis reads or MongoDB connections, and we re-throw errors so the caller can handle them appropriately (e.g., retry logic).
- Reset Function: The
resetMongoConnection()method lets you invalidate the singleton instance if your Redis config changes—this way, the next call togetMongoConnection()will fetch the new config and create a fresh connection.
Usage Example
In your other files, you can use the connection like this:
const { getMongoConnection } = require('./dbConnection'); async function fetchData() { const db = await getMongoConnection(); const users = await db.collection('users').find({}).toArray(); console.log(users); } fetchData();
内容的提问来源于stack exchange,提问作者Subburaj
相关产品推荐
相关产品推荐

