Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
DatabaseintermediateNew

MongoDB Mongoose

Share

Model data with Mongoose schemas, virtuals, and middleware

Works with OpenClaude

You are a MongoDB Mongoose expert. The user wants to model data with Mongoose schemas, virtuals, and middleware to structure and validate documents with computed properties and lifecycle hooks.

What to check first

  • Run npm list mongoose to verify Mongoose is installed and check the version
  • Confirm MongoDB connection string is available (local or Atlas URI)
  • Check if you need to define multiple related schemas or if this is a single-model task

Steps

  1. Create a Mongoose connection using mongoose.connect() with the MongoDB URI and connection options like useNewUrlParser: true
  2. Define a schema object with field names as keys and type definitions (String, Number, Date, Boolean, ObjectId) as values, including validation rules like required, minlength, maxlength, enum, or custom validators
  3. Add nested schemas or arrays of subdocuments using nested object syntax or the Schema.Types.DocumentArray type
  4. Define virtual properties using schema.virtual() to create computed fields that don't persist to the database (e.g., fullName from firstName and lastName)
  5. Add pre- and post-middleware hooks using schema.pre() and schema.post() for lifecycle events like save, validate, findOneAndUpdate, and remove
  6. Compile the schema into a Model using mongoose.model('ModelName', schema) with the exact collection name
  7. Create, query, and update documents using model methods like .create(), .find(), .findById(), .updateOne(), and .deleteOne() with proper error handling
  8. Use lean() on queries when you don't need full Mongoose document instances for better performance

Code

const mongoose = require('mongoose');

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myapp', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// Define schema with validation
const userSchema = new mongoose.Schema({
  firstName: {
    type: String,
    required: [true, 'First name is required'],
    minlength: 2,
    maxlength: 50,
  },
  lastName: {
    type: String,
    required: true,
    maxlength: 50,
  },
  email: {
    type: String,
    required: true,
    unique: true,
    match: /.+\@.+\..+/,
  },
  age: {
    type: Number,
    min: 0,
    max: 150,
  },
  role: {
    type: String,
    enum: ['user', 'admin', 'moderator'],
    default: 'user',
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  tags: [String],
  profile: {
    bio: String,
    website: String,
  },
});

// Add virtual property
userSchema.virtual

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

CategoryDatabase
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
mongodbmongooseschemas

Install command:

curl -o ~/.claude/skills/mongodb-mongoose.md https://clskills.in/skills/database/mongodb-mongoose.md

Related Database Skills

Other Claude Code skills in the same category — free to download.

Want a Database skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.