mongoose-mongodb
Skill0 starsChanged 15 days agoMITView on GitHub
MongoDB with Mongoose done right — connection handling (server and serverless), model schema requirements, indexes, .select/.lean, pagination, soft delete, $in batching instead of N+1, aggregation, transactions and duplicate-key handling. Use when writing or reviewing Mongoose models, queries or MongoDB data access in Node.js.
In this repository14 other files it gives its agents.
- ai-integrationSkill
- api-docsSkill
- auth-sessionsSkill
- backend-conventionsSkill
- backend-reviewSkill
- create-backendSkill
- deploy-dockerSkill
- new-moduleSkill
- nextjs-api-routesSkill
- prisma-postgresSkill
- redis-cacheSkill
- scheduled-jobsSkill
- security-hardeningSkill
- session-logSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 90
Use for reporting, grouping and joins you would otherwise do in a loop.
- Very specific: line 94
Use session.withTransaction only when several documents must change together (requires a replica set).
- Distinctive: line 100
Not found / not yours → 404.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 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
Mongoose / MongoDB
Connection
One connection per process, pool capped at 10, reused everywhere:
import { getMongoose } from '../config/databases.js';- Long-running server: call
connectDatabases()once inserver.jsbeforelisten; disconnect in the graceful shutdown. - Serverless / Next.js route handlers: call
await getMongoose()at the top of each service. The connection promise is cached onglobalThisso hot reloads and warm invocations reuse it, and a failed connect clears the cached promise so the next call retries. maxPoolSize: 10. Do not raise it per call site.
Model requirements
import mongoose from 'mongoose';
const orderSchema = new mongoose.Schema(
{
storeId: { type: mongoose.Schema.Types.ObjectId, ref: 'Store', required: true },
customerId: { type: mongoose.Schema.Types.ObjectId, ref: 'Customer', required: true },
status: { type: String, enum: Object.values(EOrderStatus), default: EOrderStatus.PENDING },
total: { type: Number, required: true, min: 0 },
isActive: { type: Boolean, default: true },
},
{ timestamps: true }
);
orderSchema.index({ storeId: 1, isActive: 1 });
orderSchema.index({ storeId: 1, isActive: 1, status: 1, createdAt: -1 });
export default mongoose.models.Order || mongoose.model('Order', orderSchema);Every model has:
isActive: { type: Boolean, default: true }and{ timestamps: true }.- A scope field (
storeId/orgId/userId), required and indexed. - Compound
{ scope: 1, isActive: 1 }index. - An index covering every field used in a
find/findOnefilter or sort. Compound order: equality fields first, then sort, then range (ESR). - Unique constraints that must ignore soft-deleted rows use
partialFilterExpression: { isActive: true }. enumvalues come from anE-prefixed constant, not inline strings repeated across files.trim,maxlength,minon user input fields, mirroring the Zod schema.- The
mongoose.models.X ||guard so hot reload does not throwOverwriteModelError. - Model files may need
no-invalid-this: offin ESLint (forprehooks usingthis); the override must be the last config entry.
Query rules
const [total, items] = await Promise.all([
Order.countDocuments(filter),
Order.find(filter)
.select('status total customerId createdAt')
.sort({ createdAt: -1 })
.skip((page - 1) * limit)
.limit(limit)
.lean(),
]);- Always
.select()the fields you return. Never fetch the whole document by default. - Always
.lean()on reads you do not.save()afterwards. - Always filter
isActive: trueand the scope field. Scope comes fromreq.user, never from the body. - Never query inside a loop. Collect ids and batch:
const customerIds = [...new Set(orders.map((order) => String(order.customerId)))];
const customers = await Customer.find({ _id: { $in: customerIds }, isActive: true })
.select('name phone')
.lean();
const customerById = new Map(customers.map((customer) => [String(customer._id), customer]));populate with select is fine for one level; prefer the $in + Map pattern for hot paths and anything paginated.
- Independent queries go in
Promise.all. - Updates by scope, not just
_id:findOneAndUpdate({ _id, storeId, isActive: true }, { $set: payload }, { new: true, runValidators: true }). Anullresult means 404. - Soft delete:
{ $set: { isActive: false } }. NeverdeleteOne,deleteMany,findByIdAndDelete. - Bulk changes:
updateMany/bulkWrite, never a loop ofsave(). - User-supplied search goes through a regex escape before
$regex, and is length-limited in Zod. - Unbounded reads always carry a
.limit().
Aggregation
Use for reporting, grouping and joins you would otherwise do in a loop. First stage is always $match on scope + isActive so it uses the index; $project early to drop fields. Cast string ids with new mongoose.Types.ObjectId(id) inside $match (aggregate does not auto-cast).
Transactions
Use session.withTransaction only when several documents must change together (requires a replica set). Pass { session } to every operation inside. Keep the work inside short; no external calls.
Errors
- Duplicate key
code === 11000→ 409 with a human message (handled centrally bypublicError, or throw your own when you need a specific sentence). CastErroron a bad id → 400. Validate ids in Zod (/^[a-f\d]{24}$/i) so this rarely reaches the database.- Not found / not yours → 404.
Validation alignment
Zod validates at the edge; the schema validates at the data layer. Keep limits identical (max(100) ↔ maxlength: 100).
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.

