mongoose
FreeNo executable scriptsNot checkedMongoose is an object modeling library (ODM) for MongoDB in Node.js: schemas declare fields, validation, and defaults, and models built from them run typed…
by TerminalSkills★ 221 GitHub starsAbout this skill
Mongoose — MongoDB ODM for Node.js
Overview
Mongoose is an object modeling library for MongoDB in Node.js. A schema declares fields, validation, defaults, hooks, methods, and virtuals; a model built from it casts and validates writes and returns typed documents. This skill targets Mongoose 9, which changed middleware (next() is gone), update options, and TypeScript types compared with 8.x.
Instructions
Installation
npm install mongoose # 9.x; ships its own TypeScript types, no @types package
npm install bcrypt && npm install -D @types/bcrypt # only for the password hashing in the schema example
import mongoose from "mongoose";
// Build indexes automatically everywhere except production
mongoose.set("autoIndex", process.env.NODE_ENV !== "production");
// MONGODB_URI looks like mongodb://127.0.0.1:27017/storefront
await mongoose.connect(process.env.MONGODB_URI!, { serverSelectionTimeoutMS: 5000 });
Schema Definition
Let Mongoose infer the document type from the schema, and declare virtuals, methods, and statics in the schema options so they are typed too. Do not write an interface that extends Document.
import bcrypt from "bcrypt";
import mongoose, { Schema, model, type HydratedDocumentFromSchema } from "mongoose";
const userSchema = new Schema(
{
email: {
type: String,
required: [true, "Email is required"],
unique: true, // creates the index; a second schema.index({ email: 1 }) triggers a duplicate-index warning
lowercase: true,
trim: true,
match: [/^\S+@\S+\.\S+$/, "Invalid email format"],
},
name: { type: String, required: true, minlength: 2, maxlength: 100 },
passwordHash: { type: String, required: true, select: false },
role: { type: String, enum: ["user", "admin", "moderator"], default: "user" },
profile: {
bio: { type: String, maxlength: 500 },
avatar: String,
website: { type: String, match: /^https?:\/\// },
},
posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
},
{
timestamps: true, // adds createdAt and updatedAt
toJSON: { virtuals: true },
virtuals: {
displayName: {
get() {
return `${this.name} <${this.email}>`;
},
},
},
methods: {
verifyPassword(password: string) {
return bcrypt.compare(password, this.passwordHash);
},
},
statics: {
findByEmail(email: string) {
return this.findOne({ email: email.toLowerCase() });
},
},
},
);
// Index for search
userSchema.index({ name: "text", "profile.bio": "text" });
// Pre-save middleware: an async function with no next(); throw to abort the save
userSchema.pre("save", async function () {
if (this.isModified("passwordHash")) {
this.passwordHash = await bcrypt.hash(this.passwordHash, 12);
}
});
export const User = model("User", userSchema);
export type UserDoc = HydratedDocumentFromSchema<typeof userSchema>;
Queries
// Find with filters, sorting, pagination
const users = await User.find({ role: "user" })
.sort({ createdAt: -1 })
.skip(20).limit(10)
.select("name email profile.avatar")
.lean(); // Plain objects: no getters, virtuals, or save()
// select: false fields must be requested explicitly
const account = await User.findOne({ email: "[email protected]" }).select("+passwordHash").orFail();
const ok = await account.verifyPassword("correct horse battery");
// Update: validators run only when asked; returnDocument replaces the deprecated `new: true`
const promoted = await User.findOneAndUpdate(
{ email: "[email protected]" },
{ $set: { role: "moderator" } },
{ returnDocument: "after", runValidators: true },
);
// Populate references
const userWithPosts = await User.findById(account._id)
.populate({ path: "posts", select: "title createdAt", options: { limit: 5, sort: { createdAt: -1 } } });
// Aggregation pipeline (not cast or validated by the schema)
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const stats = await User.aggregate([
{ $match: { createdAt: { $gte: thirtyDaysAgo } } },
{ $group: { _id: "$role", count: { $sum: 1 }, latest: { $max: "$createdAt" } } },
{ $sort: { count: -1 } },
]);
// Transaction: commits when the function returns, aborts when it throws, retries transient errors.
// Pass the session to every operation and do not run them in parallel.
await mongoose.connection.transaction(async (session) => {
const [post] = await Post.create([{ title: "Shipping rates for 2027", author: account._id }], { session });
await User.updateOne({ _id: account._id }, { $push: { posts: post._id } }, { session });
});
Examples
Example 1: Model with a reference and a populated query
User request: "Add a Post model that belongs to a user, and a function that returns a user's five latest posts with the author's name."
import {
Install mongoose in Claude Code & Claude Desktop
Sign up to install this skill
Create a free account to reveal the install command and save the skill to your library.
- Reveal the one-line install command
- Save skills to your synced library
- Get notified when skills update
Allowed tools
Tools this skill is permitted to call.
No restriction — this skill can use any tool.
Bundled files
FAQ
What does the mongoose skill do?
Mongoose is an object modeling library (ODM) for MongoDB in Node.js: schemas declare fields, validation, and defaults, and models built from them run typed queries, middleware hooks, population, and transactions. Use when a user asks to define a Mongoose schema or model, validate MongoDB documents, add pre/post hooks, populate references, run a transaction, type models in TypeScript, or migrate code to Mongoose 9.
How do I install the mongoose skill?
Copy the skill folder into ~/.claude/skills (the Claude Code tab above does this in one command), or install it as a plugin.
Does the mongoose skill run scripts?
No, this skill is instructions only (SKILL.md) with no executable scripts.
Related skills
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
by Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
by Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
by Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
by Anthropic