Home › MongoDB › Mongoose (MongoDB ODM) rules
Mongoose (MongoDB ODM) rules
Cursor rules for Mongoose 8 with TypeScript: typed schemas, indexes, lean queries, validation, and transactions.
CursorMongoDB
How to use
Save this as .cursor/rules/mongoose.mdc in your repository root, commit it, and your agent will pick it up automatically. Edit the commands to match your project.
Note: Review and test before use. Provided as is, without warranty. See Terms.
.cursor/rules/mongoose.mdcDownload ---
description: Mongoose (MongoDB ODM) conventions
globs: ["**/*.{ts,js}"]
alwaysApply: false
---
# Mongoose 8
- Define a TS interface per model and pass it to `new Schema<IUser>({...}, { timestamps: true })`; export `model<IUser>('User', schema)` guarded against recompilation in dev (`models.User ?? model(...)`).
- Put validation in the schema (`required`, `enum`, `min`, `match`, custom `validate`) and run validators on updates (`runValidators: true`, or set it globally).
- Declare indexes with `schema.index({ userId: 1, createdAt: -1 })`; sync them in a deploy step, not with `autoIndex` in production.
- Reads that don't need documents use `.lean()` (typed with the generic) and `.select()` projections.
- Avoid N+1 `populate` chains; populate one level, with `select`, or denormalize the needed fields.
- Updates with operators (`$set`, `$inc`, `$addToSet`) via `updateOne`/`findOneAndUpdate({ new: true })`. Middleware (`pre('save')`) doesn't run on these, so don't rely on it for update paths.
- Sanitize filters: build them from explicit fields; set `sanitizeFilter: true` (or `mongoose.set('sanitizeFilter', true)`) so `{ $ne: ... }` from user input can't inject operators.
- Transactions: `await mongoose.connection.transaction(async (session) => {...})` passing `{ session }` to every operation.
- Hide sensitive fields with `select: false` (e.g. `passwordHash`) and a `toJSON` transform.
- Connect once at startup with `mongoose.connect(process.env.MONGODB_URI)`; handle connection errors.
## Done when
Typecheck and tests (with `mongodb-memory-server` or a test container) pass.