Node Mongo db connection

Connect Node.js with MongoDB — Light Blue Guide
Tutorial

Connect Node.js with MongoDB (Local & Atlas)

A compact, production-aware guide — includes sample code, Atlas notes, and security tips.
What you'll learn:
  • How to connect Node.js to a local MongoDB instance
  • How to swap the connection string to MongoDB Atlas (cloud)
  • Practical security tips for credentials and IP access

Why MongoDB?

MongoDB is a document-oriented NoSQL database that stores flexible JSON-like documents. It's ideal for rapid development, horizontal scaling, and evolving schemas.

Use MongoDB when your data shape may change frequently — e.g., user profiles, product catalogs, logs, or session stores.

Code example — Local MongoDB

Copy the snippet below into index.js and run with node index.js. This example uses the official mongodb driver.

// index.js
const { MongoClient } = require("mongodb");

const uri = "mongodb://127.0.0.1:27017"; // Local MongoDB
// const uri = "mongodb+srv://:@cluster.mongodb.net"; // Atlas

const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    console.log("✅ Connected to MongoDB");

    const db = client.db("testdb");
    const collection = db.collection("users");

    // Insert example
    await collection.insertOne({ name: "Champak Roy", age: 22 });

    // Read example
    const users = await collection.find().toArray();
    console.log(users);

  } catch (err) {
    console.error("❌ Connection error:", err);
  } finally {
    await client.close();
  }
}

run();
Tip: Ensure mongod (the MongoDB server) is running on your machine or container before connecting.

Switch to MongoDB Atlas (cloud)

Use the connection string Atlas provides. Replace the local URI with the Atlas URI (remember to URL-encode special characters in your password):

// Example Atlas URI (replace placeholders)
const uri = "mongodb+srv://:@cluster0.abcd.mongodb.net/testdb";
  1. Create a free cluster in Atlas.
  2. Add a database user under Security → Database Access.
  3. Whitelist your IP in Network Access → IP Access List (or add 0.0.0.0/0 for quick testing — not for production).
  4. From the cluster page choose Connect → Connect your application and copy the Node.js string.

.env and security

Never hard-code credentials. Use a .env file and the dotenv package in development:

# .env
MONGODB_URI="mongodb+srv://your_user:your%40password@cluster0.abcd.mongodb.net/testdb?retryWrites=true&w=majority"
// usage in Node
require('dotenv').config();
const { MongoClient } = require('mongodb');
const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();

Security checklist: Don't commit .env to git; use a secrets manager in production; restrict IP access; and create least-privilege DB users.

Written by Champak Roy
Node.js • MongoDB • Tutorial

0 Comments

Post a Comment

0 Comments