Model data with Mongoose schemas, virtuals, and middleware
✓Works with OpenClaudeYou 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 mongooseto 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
- Create a Mongoose connection using
mongoose.connect()with the MongoDB URI and connection options likeuseNewUrlParser: true - 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 - Add nested schemas or arrays of subdocuments using nested object syntax or the
Schema.Types.DocumentArraytype - Define virtual properties using
schema.virtual()to create computed fields that don't persist to the database (e.g., fullName from firstName and lastName) - Add pre- and post-middleware hooks using
schema.pre()andschema.post()for lifecycle events likesave,validate,findOneAndUpdate, andremove - Compile the schema into a Model using
mongoose.model('ModelName', schema)with the exact collection name - Create, query, and update documents using model methods like
.create(),.find(),.findById(),.updateOne(), and.deleteOne()with proper error handling - 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
Related Database Skills
Other Claude Code skills in the same category — free to download.
Migration Generator
Generate database migration files
Query Optimizer
Analyze and optimize slow database queries
Schema Designer
Design database schema from requirements
Seed Data Generator
Generate database seed/sample data
Index Advisor
Suggest database indexes based on query patterns
ORM Model Generator
Generate ORM models from database schema
SQL to ORM
Convert raw SQL queries to ORM syntax
Database Backup Script
Create database backup and restore scripts
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.