Connecting to MongoDB
Imagine you have a giant filing cabinet where you store all your important documents. In the Node.js world, that filing cabinet is called a **database**. MongoDB is one of the most popular databases, and it works beautifully with Node.js.
What is MongoDB?
MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. Instead of tables with rows and columns (like SQL databases), MongoDB uses **collections** and **documents**.
| SQL Term | MongoDB Term |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
Think of MongoDB as a digital filing cabinet where each document can have different fields – unlike SQL where every row must have the same columns.
Installing MongoDB Driver
To connect Node.js with MongoDB, we need the official MongoDB driver. Install it in your project:
npm install mongodbSetting Up MongoDB
Before connecting, you need MongoDB installed and running. You can:
- Install MongoDB locally from MongoDB Community Server
- Use MongoDB Atlas (cloud database) – free tier available
Connecting to MongoDB (Local)
const { MongoClient } = require('mongodb');
<!-- Connection URL – local MongoDB runs on port 27017 -->const url = 'mongodb://localhost:27017';const dbName = 'myapp';
const client = new MongoClient(url);
async function connectDB() { try { <!-- Connect to the MongoDB server --> await client.connect(); console.log('Connected successfully to MongoDB'); <!-- Get the database --> const db = client.db(dbName); <!-- Now you can work with collections --> const collection = db.collection('users'); <!-- Example: insert a document --> const result = await collection.insertOne({ name: 'John', age: 30 }); console.log('Inserted document:', result.insertedId); <!-- Close the connection when done --> await client.close(); } catch (err) { console.error('Error connecting to MongoDB:', err); }}
connectDB();Connecting to MongoDB Atlas (Cloud)
If you're using MongoDB Atlas, the connection string will look different:
<!-- Format: mongodb+srv://username:password@cluster.mongodb.net/dbname -->const url = 'mongodb+srv://myuser:mypassword@cluster0.abcde.mongodb.net/myapp';Better: Using Connection Pool
In a real application, you don't want to connect and disconnect for every operation. Instead, you create a connection once and reuse it.
let db;
async function getDB() { if (db) return db; const client = new MongoClient(url); await client.connect(); db = client.db(dbName); return db;}Two Minute Drill
- MongoDB is a NoSQL database that stores data in JSON-like documents.
- Install the official driver: `npm install mongodb`.
- Connect using `MongoClient` with a connection URL.
- Local MongoDB runs at `mongodb://localhost:27017`.
- Atlas provides cloud MongoDB with a connection string.
- In production, maintain a persistent connection (connection pool).
Need more clarification?
Drop us an email at career@quipoinfotech.com
