mongoose

Mongoose expert: a Node.js MongoDB object modeling library that helps developers define validated schemas, build queries with a fluent API, use middleware hooks, populate references, create virtuals, and handle transactions—providing structure and type safety on top of MongoDB's document model.

Last repository push
GitHub Stars
219
Forks
38
Issues / PRs
7

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "mongoose" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-37cff967f087eb9081c072846ba655d122579d7abfced33b7fe19e3184330e3f. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Mongoose expert: a Node.js MongoDB object modeling library that helps developers define validated schemas, build queries with a fluent API, use middleware hooks, populate references, create virtuals, and handle transactions—providing structure and type safety on top of MongoDB's document model.

0 Downloads

Introduction source: third_party · TerminalSkills · 1.0.0 Reference

SkillPi interpretation

Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: mongoose
description: >-
  You are an expert in Mongoose, the elegant MongoDB object modeling library
  for Node.js. You help developers define schemas with validation, build
  queries with a fluent API, use middleware hooks, populate references, create
  virtual fields, and handle transactions — providing structure and type
  safety on top of MongoDB's flexible document model.
license: Apache-2.0
compatibility: ''
metadata:
  author: terminal-skills
  version: 1.0.0
  category: Backend Development
  tags:
    - mongodb
    - odm
    - schema
    - validation
    - typescript
    - node
    - database

Mongoose — MongoDB ODM for Node.js

You are an expert in Mongoose, the elegant MongoDB object modeling library for Node.js. You help developers define schemas with validation, build queries with a fluent API, use middleware hooks, populate references, create virtual fields, and handle transactions — providing structure and type safety on top of MongoDB's flexible document model.

Core Capabilities

Schema Definition

import mongoose, { Schema, Document, Model } from "mongoose";

interface IUser extends Document {
  email: string;
  name: string;
  passwordHash: string;
  role: "user" | "admin" | "moderator";
  profile: { bio?: string; avatar?: string; website?: string };
  posts: mongoose.Types.ObjectId[];
  createdAt: Date;
  updatedAt: Date;
  fullName: string;
}

const userSchema = new Schema<IUser>(
  {
    email: {
      type: String,
      required: [true, "Email is required"],
      unique: true,
      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,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

// Virtual field
userSchema.virtual("fullName").get(function () {
  return this.name;
});

// Index for search
userSchema.index({ email: 1 });
userSchema.index({ name: "text", "profile.bio": "text" });

// Pre-save middleware
userSchema.pre("save", async function (next) {
  if (this.isModified("passwordHash")) {
    this.passwordHash = await bcrypt.hash(this.passwordHash, 12);
  }
  next();
});

// Static method
userSchema.statics.findByEmail = function (email: string) {
  return this.findOne({ email: email.toLowerCase() });
};

// Instance method
userSchema.methods.verifyPassword = async function (password: string) {
  return bcrypt.compare(password, this.passwordHash);
};

const User: Model<IUser> = mongoose.model("User", 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 (faster)

// Populate references
const userWithPosts = await User.findById(id)
  .populate({ path: "posts", select: "title createdAt", options: { limit: 5, sort: { createdAt: -1 } } });

// Aggregation pipeline
const stats = await User.aggregate([
  { $match: { createdAt: { $gte: thirtyDaysAgo } } },
  { $group: { _id: "$role", count: { $sum: 1 }, latest: { $max: "$createdAt" } } },
  { $sort: { count: -1 } },
]);

// Transactions
const session = await mongoose.startSession();
await session.withTransaction(async () => {
  const user = await User.create([{ name: "Alice", email: "alice@example.com", passwordHash: "..." }], { session });
  await Post.create([{ title: "First Post", author: user[0]._id }], { session });
});

Installation

npm install mongoose

Best Practices

  1. Schema validation — Define strict schemas; use required, enum, match, min/max validators
  2. Lean queries — Use .lean() for read-only queries; returns plain objects, 5x faster than Mongoose documents
  3. Indexes — Add indexes for fields you query/sort by; use explain() to verify query plans
  4. Population — Use populate() sparingly; for complex joins, prefer aggregation $lookup
  5. Middleware — Use pre('save') for hashing, validation; post('save') for notifications, logging
  6. Timestamps — Enable timestamps: true; auto-manages createdAt and updatedAt
  7. Transactions — Use sessions for multi-document operations; requires replica set or MongoDB Atlas
  8. TypeScript — Define interfaces extending Document; use generics with Schema<IUser> for full type safety

Current listing version

1.0.0

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 提供 Mongoose 的完整使用指南,涵盖 Schema 定义、查询、中间件、事务等核心功能
  • 面向 Node.js 开发者,具有明确的实用价值和广泛的应用场景
Trigger Precision90/100

Highlights

  • description 明确描述了 Skill 的核心能力,触发词覆盖合理,边界清晰
Structure and Standards95/100

Areas to improve

  • description 内容重复 Reported severity: Minor

    顶层 frontmatter 和 skill_body 中均包含相同的 description 内容

    Recommendation: 建议移除 skill_body 中的重复 description,保持文档简洁

Highlights

  • 文档结构清晰,包含 Core Capabilities、Installation、Best Practices 等章节
  • 提供了完整的 TypeScript 代码示例,涵盖 Schema 定义、查询、聚合、事务等核心功能
Execution Reliability90/100

Highlights

  • 代码示例完整,工具来源明确(mongoose npm 包),参数使用正确
  • 覆盖了主要使用场景,包括 Schema 验证、索引、中间件、事务等关键功能
Evidence Verifiability (mean of the first four)90/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

  • Install or fetch external dependencies

    Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.

    Mentioned in main document · lines 137

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.