Home › MongoDB › MongoDB Windsurf rules
MongoDB Windsurf rules
Windsurf rules for MongoDB 8 apps with the Node.js driver: schema design, indexes, aggregation, and transactions.
WindsurfMongoDB
How to use
Save this as .windsurf/rules/mongodb.md in your repository root, commit it, and your agent will pick it up automatically. Edit the commands to match your project.
.windsurf/rules/mongodb.mdDownload ---
trigger: glob
globs: **/*.{ts,js}
---
# MongoDB (Node.js driver)
- One `MongoClient` per process, created at startup and reused (in serverless, cache it on `globalThis`). Connection string from env.
- Model data for the app's queries: embed data read together and bounded in size; reference (store ids) for unbounded or independently updated data. Documents must stay well under 16 MB.
- Type collections: `db.collection<Order>('orders')`. Validate writes with a zod schema in code and a `$jsonSchema` validator on the collection.
- Every frequent query has a supporting index (ESR rule: equality, sort, range). Create indexes in a migration/startup script, and check plans with `.explain('executionStats')` (look for `IXSCAN`, not `COLLSCAN`).
- Use projections to return only needed fields. Paginate with range queries on an indexed field (`{ _id: { $gt: lastId } }`), not big `skip`.
- Updates use operators (`$set`, `$inc`, `$push`) and atomic `findOneAndUpdate`; never read-modify-write the whole document.
- Multi-document consistency with `session.withTransaction()` (needs a replica set); keep transactions short.
- Never build queries from raw user objects (operator injection like `{ $gt: '' }`); pick fields explicitly and cast types.
- Use `ObjectId.createFromHexString` with validation for ids from URLs.
## Done when
Tests run against a real MongoDB (Testcontainers or `mongodb-memory-server`) and pass.