DEV Community

Cover image for 🗄️ MongoDB/Mongoose Cheat Sheet
AK
AK

Posted on

🗄️ MongoDB/Mongoose Cheat Sheet

1️⃣ Database Connection

const mongoose = require('mongoose');

// Connect
mongoose.connect('mongodb://localhost:27017/mydb')
  .then(() => console.log('Connected!'))
  .catch(err => console.error(err));

// Connection events [Monitoring]
mongoose.connection.on('connected', () => console.log('MongoDB connected'));
mongoose.connection.on('error', err => console.error('Connection error:', err));
mongoose.connection.on('disconnected', () => console.log('MongoDB disconnected'));
Enter fullscreen mode Exit fullscreen mode

2️⃣ Schema Definition

const taskSchema = new mongoose.Schema({
  title: "{"
    type: String,
    required: true,
    trim: true,
    minlength: 3,
    maxlength: 100
  },
  completed: {
    type: Boolean,
    default: false
  },
  description: "String,"
  priority: {
    type: String,
    enum: ['low', 'medium', 'high'],
    default: 'medium'
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
}, {
  timestamps: true  // Auto adds createdAt & updatedAt
});
Enter fullscreen mode Exit fullscreen mode

3️⃣ Model Creation

const Task = mongoose.model('Task', taskSchema);

// Alternative with collection name
const Task = mongoose.model('Task', taskSchema, 'tasks');
Enter fullscreen mode Exit fullscreen mode

4️⃣ CRUD Operations

CREATE

// Method 1: new + save
const task = new Task({ title: 'Learn MongoDB' });
await task.save();

// Method 2: create (shortcut)
const task = await Task.create({ title: 'Learn MongoDB' });

// Method 3: insertMany (bulk insert)
await Task.insertMany([
  { title: 'Task 1' },
  { title: 'Task 2' }
]);
Enter fullscreen mode Exit fullscreen mode

READ

// Find all
const tasks = await Task.find();

// Find with filter
const tasks = await Task.find({ completed: false });

// Find one
const task = await Task.findOne({ title: 'Learn MongoDB' });

// Find by ID
const task = await Task.findById('65f3a2b1c3d4e5f6a7b8c9d0');

// Find with projection (select specific fields)
const tasks = await Task.find().select('title completed');

// Find with sorting
const tasks = await Task.find().sort({ createdAt: -1 }); // -1 = desc, 1 = asc

// Find with limiting
const tasks = await Task.find().limit(10).skip(20); // Pagination

// Count documents
const count = await Task.countDocuments({ completed: true });
Enter fullscreen mode Exit fullscreen mode

UPDATE

// Update by ID and return updated doc
const task = await Task.findByIdAndUpdate(
  taskId,
  { completed: true },
  { new: true, runValidators: true }
);

// Update one (first match)
const result = await Task.updateOne(
  { title: 'Old Title' },
  { title: 'New Title' }
);

// Update many
const result = await Task.updateMany(
  { completed: false },
  { priority: 'high' }
);

// Find by ID, update, and return old doc
const oldTask = await Task.findByIdAndUpdate(taskId, { completed: true });

// Upsert (update or insert if not exists)
const task = await Task.findOneAndUpdate(
  { title: 'Unique Task' },
  { completed: true },
  { upsert: true, new: true }
);
Enter fullscreen mode Exit fullscreen mode

DELETE

// Delete by ID
const task = await Task.findByIdAndDelete(taskId);

// Delete one (first match)
const result = await Task.deleteOne({ title: 'Task to delete' });

// Delete many
const result = await Task.deleteMany({ completed: true });

// Returns: { acknowledged: true, deletedCount: 5 }
Enter fullscreen mode Exit fullscreen mode

5️⃣ Query Operators

// Comparison
Task.find({ priority: 'high' });           // Equal
Task.find({ priority: { $ne: 'low' } });    // Not equal
Task.find({ priority: { $in: ['high', 'medium'] } });  // In array
Task.find({ priority: { $nin: ['low'] } }); // Not in array
Task.find({ createdAt: { $gt: new Date('2024-01-01') } }); // Greater than
Task.find({ createdAt: { $gte: date } });   // Greater than or equal
Task.find({ createdAt: { $lt: date } });    // Less than
Task.find({ createdAt: { $lte: date } });   // Less than or equal

// Logical
Task.find({ $and: [{ completed: true }, { priority: 'high' }] });
Task.find({ $or: [{ priority: 'high' }, { completed: false }] });
Task.find({ $not: { completed: true } });

// Element
Task.find({ description: { $exists: true } });  // Field exists
Task.find({ tags: { $type: 'array' } });        // Field type check

// String/Regex
Task.find({ title: /learn/i });  // Case-insensitive regex
Task.find({ title: { $regex: 'learn', $options: 'i' } });

// Array
Task.find({ tags: 'important' });  // Array contains value
Task.find({ tags: { $all: ['important', 'urgent'] } });  // Array contains all
Task.find({ tags: { $size: 2 } });  // Array has exactly 2 elements
Enter fullscreen mode Exit fullscreen mode

6️⃣ Aggregation (Advanced Queries)

// Group by and count
const result = await Task.aggregate([
  { $group: { _id: '$completed', count: { $sum: 1 } } }
]);
// Output: [{ _id: true, count: 5 }, { _id: false, count: 10 }]

// Match + Group + Sort
const result = await Task.aggregate([
  { $match: { completed: false } },
  { $group: { _id: '$priority', count: { $sum: 1 } } },
  { $sort: { count: -1 } }
]);

// Project (transform output)
const result = await Task.aggregate([
  { $project: { title: 1, completed: 1, _id: 0 } }
]);
Enter fullscreen mode Exit fullscreen mode

7️⃣ Middleware (Hooks)

// Pre-save hook (runs before save)
taskSchema.pre('save', function(next) {
  this.updatedAt = Date.now();
  next();
});

// Post-save hook (runs after save)
taskSchema.post('save', function(doc) {
  console.log('Task saved:', doc.title);
});

// Pre-remove hook
taskSchema.pre('remove', async function(next) {
  // Clean up related data
  next();
});
Enter fullscreen mode Exit fullscreen mode

8️⃣ Virtuals (Computed Properties)

taskSchema.virtual('status').get(function() {
  return this.completed ? 'Done' : 'Pending';
});

// Access: task.status (not stored in DB, computed on-the-fly)
Enter fullscreen mode Exit fullscreen mode

9️⃣ Error Handling

try {
  await Task.create({ title: '' }); // Will fail validation
} catch (err) {
  if (err.name === 'ValidationError') {
    console.error('Validation failed:', err.errors);
  } else if (err.code === 11000) {
    console.error('Duplicate key error');
  }
}
Enter fullscreen mode Exit fullscreen mode

🔟 Common Patterns

// Pagination
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const skip = (page - 1) * limit;

const tasks = await Task.find()
  .limit(limit)
  .skip(skip)
  .sort({ createdAt: -1 });

const total = await Task.countDocuments();

// Populate (reference other collections)
const userSchema = new mongoose.Schema({
  name: String,
  tasks: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Task' }]
});

const user = await User.findById(userId).populate('tasks');
Enter fullscreen mode Exit fullscreen mode

💾 Save this cheat sheet! You'll reference it constantly when building with MongoDB.
Ready to move to Topic 3 (Authentication)? 🔐

Top comments (0)