MongoDB Intro
MongoDB with Node.js: Document Databases and Connection Setup
MongoDB is a document-oriented NoSQL database that stores records as flexible JSON-like BSON documents inside collections rather than rigid rows across SQL tables. Because JavaScript objects map directly to MongoDB documents, Node.js and MongoDB pair naturally for fast-evolving APIs, catalogs, and event logs.
Relational SQL vs MongoDB Concepts
Comparing MongoDB terms to SQL helps map familiar database concepts immediately.
| SQL Concept | MongoDB Equivalent |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document ({ _id, ... }) |
| Column | Field |
| Primary Key | _id (ObjectId by default) |
Unlike strict SQL tables, documents in the same MongoDB collection can hold nested sub-documents and arrays (like embedding tags or shippingAddress right inside an order), reducing joins for read-heavy workloads.
Connecting to MongoDB in Node.js
Install the official mongodb driver (npm install mongodb), create one shared MongoClient instance at startup, and reuse its built-in connection pool across your application instead of connecting per request.
import { MongoClient } from 'mongodb';
const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri, {
maxPoolSize: 20,
serverSelectionTimeoutMS: 5000,
});
async function pingMongo() {
try {
await client.connect();
await client.db('kodersolution_app').command({ ping: 1 });
console.log('Connected to MongoDB cleanly.');
} finally {
await client.close();
}
}
pingMongo().catch((err) => console.error('MongoDB error:', err.message));
Common Mistakes to Avoid
- Opening and closing
new MongoClient()inside every Express route: Reconnecting per request exhausts sockets and adds TLS/handshake latency. Connect once at server boot and reuseclient.db(...). - Mixing up
ObjectIdwith plain strings: Querying{ _id: '65f...' }fails to match a document whose_idis anObjectId. Convert valid 24-hex strings usingnew ObjectId(id)first. - Skipping schema validation completely: Even though MongoDB is schema-flexible, validate incoming API payloads with Zod or Mongoose/JSON Schema before writing to collections.
Frequently Asked Questions
Should I use the native mongodb driver or Mongoose?
Use the official mongodb driver for minimal overhead, direct aggregation control, and TypeScript generics; choose Mongoose if you want built-in schema validation, hooks, and model classes.
What is _id in every MongoDB document?
_id is a mandatory unique primary key per document. If you omit it during insertion, the Node.js driver generates a 12-byte ObjectId automatically.
Does MongoDB support multi-document ACID transactions?
Yes. On replica sets (including MongoDB Atlas), client.startSession() supports ACID transactions across multiple collections when needed.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.