用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/majiayu000/claude-skill-registry-data --skill api-database-mongoose命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
Guided, hands-on course teaching architects how to use Claude Code — six short modules, each built around an exercise on a bundled sandbox project (a fictional Brooklyn art museum expansion). Resumable across sessions via PROGRESS.md. Use when the user runs /learn, says they're new to Claude Code, or asks how to learn it.
Upscale and restore video in ComfyUI — both the quick local path (per-frame ESRGAN like 4x_foolhardy_Remacri via ImageUpscaleWithModel + 4x→2x supersample, with its temporal-flicker tradeoff) and temporal-aware super-resolution (SeedVR2, the newer FlashVSR) with the downscale-first restore pipeline; RIFE/FILM frame interpolation via the BUILT-IN ComfyUI 0.26 FrameInterpolate (rife_v4.26 in models/frame_interpolation/) or the ComfyUI-Frame-Interpolation pack; 2x/4x scaling, VRAM tiers, VHS encode. Captures the classic downscale→SeedVR2→RIFE recipe and the current 2026 recommendation.
Auto-tag FF&E products with categories, colors, materials, and style tags using AI. Use when the user asks to "enrich", "tag", or "categorize" products, or to fill in missing category, material, or style columns in the schedule.
正在显示 SKILL.md
基于 SOC 职业分类
| name | api-database-mongoose |
| description | MongoDB ODM with schemas, validation, middleware, and TypeScript support |
Quick Guide: Use Mongoose as the ODM layer for MongoDB. Let TypeScript infer types from schema definitions instead of duplicating interfaces. Register all middleware before calling
model()-- hooks added after compilation are silently ignored. Use.lean()for any read-only query. Pass{ session }to every operation inside a transaction or enabletransactionAsyncLocalStorage. Prefersession.withTransaction()over manual commit/abort. Use127.0.0.1instead oflocalhostin connection strings (Node.js 18+ IPv6 preference causes timeouts).
<critical_requirements>
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type, named constants)
(You MUST define all middleware (pre/post hooks) BEFORE calling model() -- hooks registered after model compilation are silently ignored with no error)
(You MUST pass { session } to EVERY operation inside a transaction -- missing session causes that operation to run outside the transaction silently)
(You MUST use .lean() for read-only queries returning API responses -- skipping lean wastes 3x memory on hydration overhead)
(You MUST use 127.0.0.1 instead of localhost in connection strings -- Node.js 18+ prefers IPv6 and localhost causes connection timeouts)
(You MUST NOT use findOneAndUpdate/updateOne and expect pre('save') to fire -- only save() and create() trigger document middleware)
(You MUST NOT use next() callbacks in pre hooks on Mongoose 9 -- use async/await instead; next() was removed in v9)
</critical_requirements>
Auto-detection: Mongoose, mongoose, mongoose.connect, Schema, model, ObjectId, populate, HydratedDocument, InferSchemaType, InferRawDocType, pre('save'), post('save'), lean, mongoose.startSession, withTransaction, discriminator, virtual, Schema.Types.ObjectId, Types.ObjectId
When to use:
Key patterns covered:
When NOT to use:
Detailed Resources:
Core Patterns:
Middleware & Lifecycle:
Relationships & Population:
Transactions & Advanced:
Mongoose provides schema-based modeling for MongoDB. Its value is the application-layer enforcement of structure, validation, middleware, and type safety on top of MongoDB's flexible document model.
Core principles:
model(). This is the single most common Mongoose bug -- hooks added after compilation are silently ignored..lean() returns plain JavaScript objects (3x less memory). Use it for every read-only query. Only skip lean when you need Mongoose document methods.{ session }. One missed session means that operation runs outside the transaction with no error.When to use Mongoose:
When NOT to use Mongoose:
Establish a single connection at application startup. Use environment variables for credentials. Never hardcode connection strings.
import mongoose from "mongoose";
const POOL_SIZE_MAX = 10;
const POOL_SIZE_MIN = 2;
const SERVER_SELECTION_TIMEOUT_MS = 5000;
const SOCKET_TIMEOUT_MS = 45000;
async function connectDatabase(): Promise<typeof mongoose> {
const uri = process.env.MONGODB_URI;
if (!uri) {
throw new Error("MONGODB_URI environment variable is required");
}
return mongoose.connect(uri, {
maxPoolSize: POOL_SIZE_MAX,
minPoolSize: POOL_SIZE_MIN,
serverSelectionTimeoutMS: SERVER_SELECTION_TIMEOUT_MS,
socketTimeoutMS: SOCKET_TIMEOUT_MS,
retryWrites: true,
retryReads: true,
});
}
export { connectDatabase };
Why good: Named constants for all numeric values, environment variable for URI, typed return, error on missing URI
// BAD: Hardcoded URI, localhost, no options
mongoose.connect("mongodb://localhost:27017/mydb");
Why bad: Hardcoded connection string leaks credentials, localhost fails on Node.js 18+ (IPv6 preference), no pool or timeout configuration
Let Mongoose infer types from the schema definition. Only use explicit interfaces when adding methods, statics, or virtuals.
import { Schema, model } from "mongoose";
const userSchema = new Schema(
{
name: { type: String, required: true, trim: true },
email: { type: String, required: true, unique: true, lowercase: true },
role: {
type: String,
enum: ["admin", "user", "moderator"] as const,
default: "user",
},
age: { type: Number, min: 0, max: 150 },
isActive: { type: Boolean, default: true },
tags: [{ type: String }],
},
{ timestamps: true },
);
// TypeScript automatically infers the document type from schema
const User = model(, userSchema);
{ , userSchema };
Why good: TypeScript infers types automatically, as const preserves enum literal types, timestamps via schema option, named exports
// BAD: Duplicating interface and schema definition
interface IUser {
name: string;
email: string;
}
const userSchema = new Schema({ name: String, email: String });
// Types drift apart -- schema allows undefined, interface says required
Why bad: Manual interface duplicates schema, they drift out of sync, no validation constraints, no error messages
When a model has instance methods, statics, or virtuals, use the full generic parameter set.
import {
Schema,
model,
type HydratedDocument,
type Model,
type Types,
} from "mongoose";
interface IUser {
email: string;
passwordHash: string;
firstName: string;
lastName: string;
role: "admin" | "user" | "moderator";
}
interface IUserMethods {
comparePassword(candidate: string): Promise<boolean>;
}
interface IUserVirtuals {
fullName: string;
}
type UserModel = Model<IUser, {}, IUserMethods, IUserVirtuals>;
type UserDocument = HydratedDocument<IUser, IUserMethods & IUserVirtuals>;
const userSchema = new Schema<
IUser,
UserModel,
,
{},
>(
{
},
{ : { : } },
);
userSchema.. = () {
;
};
userSchema.().( () {
;
});
userSchema.(, () {
(.()) {
}
});
= model<, >(, userSchema);
{ , userSchema };
{ , , };
Why good: Separate interfaces for document, methods, virtuals; correct generic parameter order; HydratedDocument exported for consumers; middleware before model()
See examples/core.md for the complete implementation with all generic parameters.
// Create -- triggers save middleware
const user = await User.create({ name: "Alice", email: "alice@example.com" });
// Read with lean (read-only response)
const PAGE_SIZE = 20;
const users = await User.find({ isActive: true })
.select("name email role")
.sort({ createdAt: -1 })
.limit(PAGE_SIZE)
.lean();
// Update with save() -- triggers pre('save') middleware
const doc = await User.findById(id);
if (!doc) throw new Error(`User not found: ${id}`);
doc.name = "Updated";
await doc.save();
// Direct update -- does NOT trigger save middleware
await User.findByIdAndUpdate(
id,
{ $set: { name: "Updated" } },
{
new: true,
: ,
},
);
Why good: .lean() for read-only, save() when middleware matters, { new: true, runValidators: true } on direct updates
// BAD: lean() then trying to save
const user = await User.findById(id).lean();
user.name = "Updated";
await user.save(); // TypeError: user.save is not a function
Why bad: .lean() returns plain objects without Mongoose methods -- .save() does not exist
const MIN_NAME_LENGTH = 2;
const MAX_NAME_LENGTH = 100;
const SKU_PATTERN = /^[A-Z]{2}-\d{6}$/;
const productSchema = new Schema({
name: {
type: String,
required: [true, "Product name is required"],
minlength: [
MIN_NAME_LENGTH,
`Name must be at least ${MIN_NAME_LENGTH} characters`,
],
maxlength: [
MAX_NAME_LENGTH,
`Name must be at most ${MAX_NAME_LENGTH} characters`,
],
},
price: {
type: Number,
required: true,
min: [0, "Price cannot be negative"],
validate: {
validator: (v: number) => Number.isFinite(v),
message: "Price must be a finite number",
},
},
sku: {
type: String,
required: true,
unique: true,
: [, ],
},
: {
: ,
: {
: [, , ] ,
: ,
},
: ,
},
});
{ productSchema };
Why good: Named constants for validation limits, custom error messages on every validator, regex validation with descriptive message, enum with as const for TypeScript inference
See examples/core.md for subdocument schemas and array validation.
<red_flags>
High Priority Issues:
model() call -- hooks are silently ignored, no error thrownPromise.all()) -- MongoDB does not support parallel operations within a single transaction session{ session } on any operation inside a transaction -- that operation runs outside the transaction silentlylocalhost in connection strings on Node.js 18+ -- IPv6 preference causes connection timeouts, use 127.0.0.1.lean() and calling .save() -- lean returns plain objects without Mongoose methodsMedium Priority Issues:
findOneAndUpdate/updateOne and expecting pre('save') to fire -- only save() and create() trigger document middleware.populate() without limit or field selection -- can return thousands of documents per populate call, each is a separate DB round-triprunValidators: true on findOneAndUpdate -- schema validation is skipped by default on direct updatesSchema.Types.ObjectId in TypeScript interfaces -- use Types.ObjectId for interfaces, Schema.Types.ObjectId for schema definitions onlyCommon Mistakes:
{ new: true } on findOneAndUpdate -- returns the old document by default, not the updated onenext() callbacks in pre hooks on Mongoose 9 -- next() was removed in v9, use async/await.lean() on write operations -- lean is for reads onlydoc.isNew in post('save') hooks -- always false after save; capture in pre('save') via this.$locals.wasNewextends Document on interfaces -- deprecated pattern that breaks type inference for lean documents and query filtersGotchas & Edge Cases:
deleteOne/deleteMany on the Model do not trigger document pre('deleteOne') middleware -- they trigger query middleware instead; use doc.deleteOne() for document middlewaretoJSON()/toObject() by default -- set { toJSON: { virtuals: true } } in schema options or they disappear in API responsesinsertMany() does not trigger save middleware -- it triggers insertMany model middleware onlyFilterQuery to QueryFilter -- update TypeScript imports if upgrading{ updatePipeline: true } or they throwcreate() with an array requires array syntax for { session }: Model.create([data], { session }) -- the non-array form Model.create(data, { session }) does not work in transactions</red_flags>
<critical_reminders>
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type, named constants)
(You MUST define all middleware (pre/post hooks) BEFORE calling model() -- hooks registered after model compilation are silently ignored with no error)
(You MUST pass { session } to EVERY operation inside a transaction -- missing session causes that operation to run outside the transaction silently)
(You MUST use .lean() for read-only queries returning API responses -- skipping lean wastes 3x memory on hydration overhead)
(You MUST use 127.0.0.1 instead of localhost in connection strings -- Node.js 18+ prefers IPv6 and localhost causes connection timeouts)
(You MUST NOT use findOneAndUpdate/updateOne and expect pre('save') to fire -- only save() and create() trigger document middleware)
(You MUST NOT use next() callbacks in pre hooks on Mongoose 9 -- use async/await instead; next() was removed in v9)
Failure to follow these rules will cause silent middleware bypass, transaction isolation failures, or connection timeouts.
</critical_reminders>