How to connect Node.js to MongoDB

Connecting Node.js to MongoDB enables persistent data storage for web applications using one of the most popular NoSQL database solutions. As the creator of CoreUI with extensive Node.js experience since 2014, I’ve connected Node.js applications to MongoDB in countless production systems for user data, content management, and analytics. The most reliable approach uses the official MongoDB driver with connection pooling and proper error handling. This method provides robust database connectivity while handling connection failures and maintaining optimal performance.

Use the official MongoDB driver with connection pooling to establish a reliable database connection.

const { MongoClient } = require('mongodb')

class DatabaseConnection {
    constructor() {
        this.client = null
        this.db = null
    }

    async connect() {
        try {
            const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017'
            const dbName = process.env.DB_NAME || 'myapp'

            this.client = new MongoClient(uri, {
                maxPoolSize: 10,
                serverSelectionTimeoutMS: 5000,
                socketTimeoutMS: 45000
            })

            await this.client.connect()
            this.db = this.client.db(dbName)

            console.log('Connected to MongoDB successfully')
            return this.db
        } catch (error) {
            console.error('MongoDB connection error:', error)
            throw error
        }
    }

    async close() {
        if (this.client) {
            await this.client.close()
            console.log('MongoDB connection closed')
        }
    }

    getDatabase() {
        if (!this.db) {
            throw new Error('Database not connected')
        }
        return this.db
    }
}

// Usage
const dbConnection = new DatabaseConnection()

async function startServer() {
    try {
        await dbConnection.connect()

        // Use database
        const db = dbConnection.getDatabase()
        const users = db.collection('users')

        // Example operation
        const user = await users.findOne({ email: '[email protected]' })
        console.log('User found:', user)

    } catch (error) {
        console.error('Application startup error:', error)
    }
}

startServer()

This code creates a MongoDB connection using the official driver with connection pooling for optimal performance. The connection class handles both connection establishment and cleanup, with proper error handling for connection failures. Environment variables are used for connection configuration, making it suitable for different deployment environments.

Best Practice Note:

This is the MongoDB connection pattern we use in CoreUI backend services for reliable data persistence. Always implement connection retry logic and monitor connection health in production applications to ensure database availability.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team