</>
Skip to content
Node.js lessons (40/44)

Node.js — MongoDB

Installation

npm install mongoose

Connection

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mydb')
    .then(() => console.log('Connected to MongoDB'))
    .catch(err => console.error('Connection error:', err));

Schema and Model

const userSchema = new mongoose.Schema({
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    age: { type: Number, min: 0 },
    createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);

CRUD Operations

// Create
const user = await User.create({ name: 'John', email: 'john@example.com' });

// Read
const users = await User.find({ age: { $gte: 18 } });
const user = await User.findById(id);

// Update
await User.findByIdAndUpdate(id, { name: 'Jane' });

// Delete
await User.findByIdAndDelete(id);

Querying

// Find with conditions
const users = await User.find({ name: 'John', age: { $gt: 25 } });

// Sort and limit
const users = await User.find().sort({ name: 1 }).limit(10);

// Select specific fields
const users = await User.find().select('name email');

Mini Practice

  1. Connect to MongoDB
  2. Create a schema
  3. Perform CRUD operations
  4. Query with conditions

Up Next

Continue with PostgreSQL — PostgreSQL integration.

Related Topics

Frequently Asked Questions about MongoDB

What is MongoDB in Node.js?

MongoDB is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn MongoDB?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn MongoDB.

Why is MongoDB important in Node.js?

MongoDB is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.