Lesson 13 of 18

Mongoose ODM

Setting Up Mongoose

Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It provides schema-based solutions with validation, casting, and business logic.

Example
// Install Mongoose
// npm install mongoose

const mongoose = require('mongoose');

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

// Connection events
mongoose.connection.on('error', err => console.error(err));
mongoose.connection.on('disconnected', () => console.log('Disconnected'));

Schemas and Models

Mongoose schemas define the structure, types, and validation for your documents. Models are constructors compiled from schemas.

Example
const { Schema, model } = require('mongoose');

// Define schema
const userSchema = new 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' },
  hobbies: [String],
  createdAt: { type: Date, default: Date.now }
});

// Create model
const User = model('User', userSchema);

// Use the model
const alice = new User({ name: 'Alice', email: 'alice@example.com', age: 28 });
await alice.save();

// Or use create()
const bob = await User.create({ name: 'Bob', email: 'bob@example.com' });

CRUD with Mongoose

Mongoose provides methods for all CRUD operations with a clean, promise-based API.

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

// Read
const users = await User.find({ role: 'admin' });
const one = await User.findById('64abc...');
const byEmail = await User.findOne({ email: 'alice@example.com' });

// Update
await User.findByIdAndUpdate('64abc...', { age: 30 }, { new: true });
await User.updateMany({ role: 'user' }, { $set: { active: true } });

// Delete
await User.findByIdAndDelete('64abc...');
await User.deleteMany({ active: false });