Mongoose (MongoDB)/Cheat sheet
Last edited by dave on 01/12/2025, 13:21:28 UTC
Mongoose (MongoDB) / Cheat sheet
Contents
Your essential quick reference for using Mongoose โ the elegant, schema-based ODM (Object Data Modeling) library for MongoDB and Node.js. ๐๐
It brings structure to your NoSQL chaos and makes working with MongoDB feel like magic.
โ๏ธ Setup
Install Dependencies
npm install mongoose
Connect to MongoDB
import mongoose from "mongoose"; mongoose.connect("mongodb://localhost:27017/mydb") .then(() => console.log("โ Connected to MongoDB")) .catch(err => console.error("โ Connection failed", err));
With MongoDB Atlas:
mongoose.connect("mongodb+srv://user:pass@cluster0.mongodb.net/mydb?retryWrites=true&w=majority");
๐งฑ Defining Schemas & Models
Basic Schema
import { Schema, model } from "mongoose"; const userSchema = new Schema({ name: { type: String, required: true }, email: { type: String, unique: true, required: true }, age: Number, createdAt: { type: Date, default: Date.now }, }); const User = model("User", userSchema);
Schema Options
| Option | Description |
|---|---|
required | Field must be provided |
unique | Unique index |
default | Default value |
min / max | For numbers |
enum | Restrict to listed values |
validate | Custom validator function |
Example:
age: { type: Number, min: 18, max: 100 }, role: { type: String, enum: ["user", "admin", "guest"] },
๐งฉ Creating Documents
Save a Document
const user = new User({ name: "Alice", email: "a@example.com" }); await user.save();
Create Shortcut
await User.create({ name: "Bob", email: "b@example.com" });
Insert Many
await User.insertMany([ { name: "Tom" }, { name: "Jerry" }, ]);
๐ Reading Documents
Find All
const users = await User.find();
Find One
const user = await User.findOne({ email: "a@example.com" });
Find by ID
const user = await User.findById("66f4abc123...");
Query Filters
await User.find({ age: { $gte: 18, $lte: 30 } }); await User.find({ name: /bob/i }); // regex await User.find().sort({ age: -1 }).limit(5).skip(10);
โ๏ธ Updating Documents
Update One
await User.updateOne({ name: "Alice" }, { age: 28 });
Update Many
await User.updateMany({ age: { $lt: 18 } }, { underage: true });
Find and Update
const updated = await User.findOneAndUpdate( { email: "a@example.com" }, { name: "Alicia" }, { new: true } );
Save Changes
const user = await User.findById(id); user.age = 30; await user.save();
๐๏ธ Deleting Documents
await User.deleteOne({ email: "a@example.com" }); await User.deleteMany({ age: { $lt: 13 } }); await User.findByIdAndDelete("66f4abc...");
๐ Relationships (Population)
Define Reference
const postSchema = new Schema({ title: String, content: String, author: { type: Schema.Types.ObjectId, ref: "User" }, }); const Post = model("Post", postSchema);
Populate Data
const posts = await Post.find().populate("author", "name email");
๐งฉ Embedded Documents (Subdocuments)
const commentSchema = new Schema({ text: String, date: { type: Date, default: Date.now }, }); const blogSchema = new Schema({ title: String, comments: [commentSchema], }); const Blog = model("Blog", blogSchema); await Blog.create({ title: "My Blog", comments: [{ text: "Great post!" }], });
๐งฎ Aggregation Pipeline
const stats = await User.aggregate([ { $match: { age: { $gte: 18 } } }, { $group: { _id: null, avgAge: { $avg: "$age" } } }, ]);
Common operators:
| Operator | Purpose |
|---|---|
$match | Filter |
$group | Aggregate |
$project | Select fields |
$sort | Sort results |
$limit / $skip | Pagination |
$lookup | Join collections |
๐งพ Query Operators
| Operator | Example | Description |
|---|---|---|
$eq | { age: { $eq: 25 } } | Equals |
$ne | { age: { $ne: 30 } } | Not equal |
$gt / $gte | { age: { $gte: 18 } } | Greater than |
$lt / $lte | { age: { $lt: 65 } } | Less than |
$in / $nin | { role: { $in: ['admin', 'user'] } } | Match list |
$exists | { email: { $exists: true } } | Field presence |
$regex | { name: { $regex: /^A/ } } | Regex search |
๐งฐ Indexes
Create Index
userSchema.index({ email: 1 });
Unique Index
userSchema.index({ email: 1 }, { unique: true });
Compound Index
postSchema.index({ author: 1, createdAt: -1 });
๐ Validation
const userSchema = new Schema({ email: { type: String, required: true, validate: { validator: (v) => /@/.test(v), message: (props) => `${props.value} is not a valid email!`, }, }, });
๐ Middleware (Hooks)
| Hook Type | Example | Description |
|---|---|---|
pre('save') | Validate or modify data before save | |
post('save') | Trigger after saving | |
pre('find') | Modify query before execution |
Example:
userSchema.pre("save", function (next) { console.log("About to save:", this.name); next(); });
๐งฎ Virtuals
Computed properties not stored in the DB.
userSchema.virtual("info").get(function () { return `${this.name} (${this.email})`; }); const user = await User.findOne(); console.log(user.info); // "Alice (a@example.com)"
๐งพ Transactions (with Sessions)
Requires MongoDB Replica Set or Atlas cluster.
const session = await mongoose.startSession(); session.startTransaction(); try { await User.create([{ name: "Alice" }], { session }); await Post.create([{ title: "Post" }], { session }); await session.commitTransaction(); } catch (err) { await session.abortTransaction(); } session.endSession();
๐งฐ Utility
Count
await User.countDocuments({ active: true });
Distinct
await User.distinct("role");
Lean Queries (Faster, no Mongoose overhead)
await User.find().lean();
โก Performance Tips
- Use
.lean()for read-heavy operations. - Always index frequently queried fields.
- Limit deep population โ prefer multiple queries.
- Use
bulkWrite()for mass updates. - Avoid unbounded queries โ always
limit(). - Enable connection pooling for scalability.
๐งพ TL;DR Mind Map
| Area | Command / Method | Description |
|---|---|---|
| Connect | mongoose.connect() | Connect to DB |
| Model | model("User", schema) | Create model |
| Create | Model.create() | Insert document |
| Read | Model.find() | Query documents |
| Update | Model.updateOne() | Modify data |
| Delete | Model.deleteMany() | Remove data |
| Populate | .populate("ref") | Join related data |
| Aggregate | .aggregate([]) | Analytics |
| Middleware | .pre(), .post() | Hooks |
| Virtual | .virtual() | Computed fields |
๐ Fun Facts
- Mongoose was first released in 2010 and remains the most popular ODM for Node.js.
- It brings schema validation to MongoDBโs schema-less design.
- Mongoose models are like โsmart wrappersโ around collections โ enforcing consistency.
- It even supports TypeScript out of the box via types!
- MongoDB + Mongoose = JSONโs happy place.
Backlinks (2)
- General
- User
No backlinks yet.
- Redirects
- Media
No backlinks yet.
- Categories
No backlinks yet.
Categories (0)
No categories assigned to this page.
Edit Level
> Signed In Users
Latest on Lounge
Join the conversation about the 'Mongoose (MongoDB)/Cheat sheet' article โ
No comments yet. Be the first to comment!