Mongoose (MongoDB)/Cheat sheet

Last edited by dave on 01/12/2025, 13:21:28 UTC

Mongoose (MongoDB) / Cheat sheet

You were redirected here from Mongoose/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

OptionDescription
requiredField must be provided
uniqueUnique index
defaultDefault value
min / maxFor numbers
enumRestrict to listed values
validateCustom 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:

OperatorPurpose
$matchFilter
$groupAggregate
$projectSelect fields
$sortSort results
$limit / $skipPagination
$lookupJoin collections

๐Ÿงพ Query Operators

OperatorExampleDescription
$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 TypeExampleDescription
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

AreaCommand / MethodDescription
Connectmongoose.connect()Connect to DB
Modelmodel("User", schema)Create model
CreateModel.create()Insert document
ReadModel.find()Query documents
UpdateModel.updateOne()Modify data
DeleteModel.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)
Categories (0)

    No categories assigned to this page.

Edit Level

> Signed In Users