backend-model-creation
Skill1 starsChanged 10 months agoMITView on GitHub
Create a new Mongoose model with proper typing, utilities, and patterns. Use when asked to "create a model", "add a data model", "create a schema", or "add a new entity".
In this repository14 other files it gives its agents.
- AGENTS.mdAGENTS.md
- skill-creatorSkill
- backend-ai-agentSkill
- backend-ai-toolsSkill
- backend-auth-clerkSkill
- backend-compressionSkill
- backend-metricsSkill
- backend-route-creationSkill
- backend-scaffoldingSkill
- backend-websocketSkill
- frontend-auth-clerkSkill
- frontend-hooks-creationSkill
- frontend-scaffoldingSkill
- new-project-scaffoldingSkill
The file
We split this skill into the rules it gives an agent
12 rules. About 0 are common, 5 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 14
Create Mongoose model in backend importing those types
- Distinctive: line 15
Use shared enum options for validation
- Very specific: line 132
Always import from _utils:
- Very specific: line 143
Always use this pattern for the id field:
- Distinctive: line 165
Always include these options to ensure clean API responses:
- Distinctive: line 340
After creating a new model:
- Very specific: line 352
Import types and enum options from @{project}/types
- Very specific: line 353
Import generateId and stripId from ./_utils
- Very specific: line 354
Create subdocument schemas with { _id: false }
- Very specific: line 355
Add schema options: id: false, versionKey: false, transforms
- Distinctive: line 356
Add indexes for common queries
- Very specific: line 357
Add pre-save hook for updatedAt
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Backend Model Creation
This skill creates Mongoose models following established patterns with proper typing from @{project}/types.
Overview
Models follow a types-first approach:
- Define TypeScript types in
@{project}/types - Create Mongoose model in backend importing those types
- Use shared enum options for validation
File Structure
libs/types/src/
├── lib/
│ ├── Workflow.ts # Type definitions
│ └── {Resource}.ts # New resource types
└── index.ts # Re-exports
apps/backend/src/models/
├── _utils.ts # generateId, stripId helpers
├── Workflow.ts # Mongoose model
└── {Resource}.ts # New resource modelStep 1: Create Types in @{project}/types
Create libs/types/src/lib/{Resource}.ts:
// Define enum options as const arrays (used for both TS types and Mongoose validation)
export const ResourceStatusOptions = ['active', 'inactive', 'archived'] as const;
export type ResourceStatus = typeof ResourceStatusOptions[number];
// Optional: Additional enum options
export const ResourcePriorityOptions = ['low', 'medium', 'high'] as const;
export type ResourcePriority = typeof ResourcePriorityOptions[number];
// Subdocument types (if needed)
export type ResourceMetadata = {
source?: string;
tags?: string[];
priority?: ResourcePriority;
};
// Main entity type
export type Resource = {
id: string;
name: string;
description?: string;
status: ResourceStatus;
metadata?: ResourceMetadata;
createdAt: Date;
updatedAt: Date;
};Export from libs/types/src/index.ts:
export * from './lib/Resource';Step 2: Create the Mongoose Model
Create apps/backend/src/models/{Resource}.ts:
import { Schema, model, Document, Types } from 'mongoose';
import {
Resource as IResource,
ResourceStatusOptions,
ResourcePriorityOptions,
} from '@{project}/types';
import { generateId, stripId } from './_utils';
// Subdocument schema (if needed)
const MetadataSchema = new Schema(
{
source: { type: String },
tags: { type: [String], default: undefined },
priority: { type: String, enum: ResourcePriorityOptions },
},
{ _id: false }
);
// Main schema
const resourceSchema = new Schema<IResource>(
{
id: { type: String, required: true, unique: true, index: true, default: generateId },
name: { type: String, required: true },
description: { type: String },
status: { type: String, enum: ResourceStatusOptions, required: true, default: 'active' },
metadata: { type: MetadataSchema },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
},
{
id: false, // Disable Mongoose's virtual id (we use our own)
versionKey: false, // Disable __v field
toJSON: { transform: stripId },
toObject: { transform: stripId },
}
);
// Compound indexes for common queries
resourceSchema.index({ status: 1, createdAt: -1 });
// Pre-save hook to update timestamp (Mongoose 8+ - no next() callback)
resourceSchema.pre('save', function () {
this.updatedAt = new Date();
});
// Export document type for services
export type ResourceDocument = Document<unknown, object, IResource> &
IResource & { _id: Types.ObjectId };
const Resource = model<IResource>('Resource', resourceSchema);
export default Resource;Key Patterns
Utilities from _utils.ts
Always import from _utils:
import { generateId, stripId } from './_utils';generateId: UUID v4 wrapper for generating unique IDsstripId: Transform helper to remove_idfrom JSON/object output
ID Field Pattern
Always use this pattern for the id field:
id: { type: String, required: true, unique: true, index: true, default: generateId },Enum Options Pattern
Define options as const arrays in types:
// In @{project}/types
export const StatusOptions = ['active', 'inactive'] as const;
export type Status = typeof StatusOptions[number];
// In Mongoose model
import { StatusOptions } from '@{project}/types';
status: { type: String, enum: StatusOptions, required: true, default: 'active' },Schema Options
Always include these options to ensure clean API responses:
{
id: false, // Disable Mongoose's virtual id
versionKey: false, // Disable __v field
toJSON: { transform: stripId },
toObject: { transform: stripId },
}Subdocument Schemas
For embedded documents, always disable _id:
const AddressSchema = new Schema(
{
street: { type: String, required: true },
city: { type: String, required: true },
zipCode: { type: String },
},
{ _id: false }
);
// Use in main schema
address: { type: AddressSchema }Array Fields
For optional arrays, use default: undefined to avoid empty arrays:
tags: { type: [String], default: undefined },For required arrays with default empty:
items: { type: [ItemSchema], required: true, default: [] },Indexes
Single field indexes:
id: { type: String, index: true },Compound indexes (add after schema definition):
// Put equality filters first, then sort fields
resourceSchema.index({ status: 1, createdAt: -1 });
resourceSchema.index({ userId: 1, status: 1 });Pre-save Hook
Mongoose 8+ uses synchronous hooks (no next() callback):
resourceSchema.pre('save', function () {
this.updatedAt = new Date();
});Document Type Export
Export the document type for use in services:
export type ResourceDocument = Document<unknown, object, IResource> &
IResource & { _id: Types.ObjectId };Complete Example
Types (libs/types/src/lib/Project.ts)
export const ProjectStatusOptions = ['planning', 'active', 'completed', 'archived'] as const;
export type ProjectStatus = typeof ProjectStatusOptions[number];
export const ProjectPriorityOptions = ['low', 'medium', 'high', 'critical'] as const;
export type ProjectPriority = typeof ProjectPriorityOptions[number];
export type ProjectMember = {
userId: string;
role: 'owner' | 'editor' | 'viewer';
joinedAt: Date;
};
export type Project = {
id: string;
name: string;
description?: string;
status: ProjectStatus;
priority: ProjectPriority;
members: ProjectMember[];
ownerId: string;
startDate?: Date;
dueDate?: Date;
completedAt?: Date;
createdAt: Date;
updatedAt: Date;
};Model (apps/backend/src/models/Project.ts)
import { Schema, model, Document, Types } from 'mongoose';
import {
Project as IProject,
ProjectStatusOptions,
ProjectPriorityOptions,
} from '@{project}/types';
import { generateId, stripId } from './_utils';
// Member subdocument schema
const MemberSchema = new Schema(
{
userId: { type: String, required: true },
role: { type: String, enum: ['owner', 'editor', 'viewer'], required: true },
joinedAt: { type: Date, default: Date.now },
},
{ _id: false }
);
// Main Project schema
const projectSchema = new Schema<IProject>(
{
id: { type: String, required: true, unique: true, index: true, default: generateId },
name: { type: String, required: true },
description: { type: String },
status: { type: String, enum: ProjectStatusOptions, required: true, default: 'planning' },
priority: { type: String, enum: ProjectPriorityOptions, required: true, default: 'medium' },
members: { type: [MemberSchema], required: true, default: [] },
ownerId: { type: String, required: true, index: true },
startDate: { type: Date },
dueDate: { type: Date },
completedAt: { type: Date },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
},
{
id: false,
versionKey: false,
toJSON: { transform: stripId },
toObject: { transform: stripId },
}
);
// Indexes
projectSchema.index({ ownerId: 1, status: 1 });
projectSchema.index({ status: 1, dueDate: 1 });
// Pre-save hook
projectSchema.pre('save', function () {
this.updatedAt = new Date();
});
// Document type
export type ProjectDocument = Document<unknown, object, IProject> &
IProject & { _id: Types.ObjectId };
const Project = model<IProject>('Project', projectSchema);
export default Project;Checklist
After creating a new model:
- Create types in
libs/types/src/lib/{Resource}.ts- Define enum options as
constarrays - Define subdocument types if needed
- Define main entity type
- Define enum options as
- Export types from
libs/types/src/index.ts - Build types library:
npx tsc -b libs/types/tsconfig.lib.json - Create model in
apps/backend/src/models/{Resource}.ts- Import types and enum options from
@{project}/types - Import
generateIdandstripIdfrom./_utils - Create subdocument schemas with
{ _id: false } - Add schema options:
id: false,versionKey: false, transforms - Add indexes for common queries
- Add pre-save hook for
updatedAt - Export document type
- Import types and enum options from
- Create API schemas (if needed) in
libs/types/src/api/{resource}.ts(see backend-route-creation skill) - Create routes (if needed) in
apps/backend/src/routes/{resource}.ts(see backend-route-creation skill)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

