Connecting Node.js with MongoDB

📘 Node.js 👁 53 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

MongoDB is a NoSQL, document-oriented database that stores data in JSON-like documents.
Connecting Node.js with MongoDB enables applications to handle flexible, scalable, and schema-less data.


1. Why Use MongoDB with Node.js?

  • JSON-like data fits naturally with JavaScript

  • Schema flexibility

  • High scalability and performance

  • Ideal for modern web and API-based applications


2. Required Package

Node.js connects to MongoDB using:

  • mongodb (official driver)

  • mongoose (ODM – Object Data Modeling)

Install MongoDB Driver

npm install mongodb

3. Connecting Using MongoDB Native Driver

3.1 Import MongoDB Client

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

3.2 Create Connection URL

const url = 'mongodb://localhost:27017'; const client = new MongoClient(url);

3.3 Connect to Database

async function connectDB() { await client.connect(); console.log('Connected to MongoDB'); const db = client.db('testdb'); } connectDB();

4. Performing Database Operations

4.1 Insert Data

const users = db.collection('users'); await users.insertOne({ name: 'Alice', age: 25 });

4.2 Read Data

const result = await users.find({ age: 25 }).toArray(); console.log(result);

4.3 Update Data

await users.updateOne( { name: 'Alice' }, { $set: { age: 26 } } );

4.4 Delete Data

await users.deleteOne({ name: 'Alice' });

5. Using MongoDB with Express.js

app.get('/users', async (req, res) => { const users = await db.collection('users').find().toArray(); res.json(users); });

6. Connecting Using Mongoose (Popular Approach)

Install Mongoose

npm install mongoose

Connect to MongoDB

const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/testdb') .then(() => console.log('MongoDB Connected')) .catch(err => console.error(err));

Define Schema and Model

const userSchema = new mongoose.Schema({ name: String, age: Number }); const User = mongoose.model('User', userSchema);

CRUD with Mongoose

const user = new User({ name: 'Bob', age: 30 }); await user.save();

7. MongoDB Native Driver vs Mongoose

MongoDB DriverMongoose
Low-level APIHigh-level abstraction
Manual validationSchema-based validation
More controlEasier to use

8. Best Practices

  • Use environment variables for DB URLs

  • Handle connection errors properly

  • Close connections when required

  • Use indexes for performance


9. Typical Application Flow

Client Request ↓ Express Route ↓ MongoDB Query ↓ Database Response ↓ JSON Response

10. Summary

  • MongoDB integrates smoothly with Node.js

  • Supports flexible, document-based storage

  • Can be used via native driver or Mongoose

  • Common choice for REST APIs and scalable apps


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes