0PricingLogin
MongoDB Academy · Lesson

Connecting With the Official Node.js Driver

Learners will create a MongoClient, manage the connection pool, and run CRUD operations from a Node.js application using the native driver.

The Official MongoDB Node.js Driver

The MongoDB Node.js driver (mongodb npm package) is the official, low-level library for connecting to MongoDB from Node.js applications. It provides direct access to all MongoDB features without an abstraction layer, making it ideal for performance-critical code, microservices, and scripts. The driver is maintained by MongoDB, Inc. and closely tracks new MongoDB server features.

// Install the driver
// npm install mongodb

// Or with yarn:
// yarn add mongodb

// The driver exports MongoClient as its main entry point
const { MongoClient, ObjectId, ServerApiVersion } = require('mongodb');
// or ES module:
// import { MongoClient, ObjectId } from 'mongodb';

Creating a MongoClient

The MongoClient class is the entry point for all interactions. Instantiate it with your connection string (URI) and an optional options object. The connection string encodes the host, port, credentials, and connection parameters. For MongoDB Atlas, copy the connection string from the Atlas UI and replace the placeholder password. Create one MongoClient per application and reuse it—do not create a new one per request.

const { MongoClient, ServerApiVersion } = require('mongodb');

const uri = process.env.MONGODB_URI;
// URI format: mongodb+srv://<user>:<password>@cluster0.xxxxx.mongodb.net/?retryWrites=true

const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true
  }
});

// client is not yet connected — connecting happens lazily or via connect()

All lessons in this course

  1. Connecting With the Official Node.js Driver
  2. Mongoose Schemas, Models, and Virtuals
  3. Mongoose Queries, Chaining, and Lean Documents
  4. Mongoose Middleware: Pre and Post Hooks
← Back to MongoDB Academy