Node.js + MongoDB — Mongoose ODM Complete Guide

Connect Node.js to MongoDB with Mongoose: schemas, models, CRUD operations, population, indexing, and aggregation.

Node.js Intermediate 📖 11 min

Setting Up Mongoose

const mongoose = require('mongoose');

await mongoose.connect('mongodb://localhost:27017/myapp', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

Defining Schemas

const userSchema = new mongoose.Schema({
  name: { type: String, required: true, trim: true },
  email: { type: String, required: true, unique: true, lowercase: true },
  age: { type: Number, min: 0, max: 150 },
  role: { type: String, enum: ['user', 'admin'], default: 'user' },
  posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
}, { timestamps: true });

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

CRUD Operations

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

// Read
const users = await User.find({ role: 'user' }).sort('-createdAt').limit(10);
const user = await User.findById(id).populate('posts');

// Update
const updated = await User.findByIdAndUpdate(id, { name: 'Bob' }, { new: true });

// Delete
await User.findByIdAndDelete(id);

Aggregation Pipeline

const stats = await User.aggregate([
  { $match: { role: 'user' } },
  { $group: {
    _id: '$department',
    avgAge: { $avg: '$age' },
    count: { $sum: 1 }
  }},
  { $sort: { count: -1 } }
]);

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →