mongoose
БесплатноБез исполняемых скриптовНе проверен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…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
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 {
Установить mongoose в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл mongoose?
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.
Как установить скилл mongoose?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл mongoose запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
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…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от 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…
от Anthropic